个人整理Python代码实例

本文集合了Python编程中常见的代码实例,包括验证码生成、时间格式化、登录日志记录、自动回复模拟、数学运算、闰年判断及字符串分析等,为初学者和开发者提供了丰富的实践案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1。四位数字字母验证码的生成实例

 1 import random    
 2 if __name__ =="__main__":    #四位数字字母验证码的生成
 3     checkcode="" #保存验证码的变量
 4     for i in range(4):
 5         index=random.randrange(0,4)  #生成一个0~3中的数
 6         if index!=i and index +1 !=i:
 7             checkcode +=chr(random.randint(97,122))  # 生成a~z中的一个小写字母
 8         elif index +1==i:
 9             checkcode +=chr(random.randint(65,90) ) # 生成A~Z中的一个大写字母
10         else:
11             checkcode +=str(random.randint(1,9))  # 数字1-9
12     print(checkcode)

输出为:m47A、8wQ9、vugS

-------------------------------

2。格式化时间函数

1 def formatTime(longtime):
2 '''格式化时间的函数'''
3 import time
4 return time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(longtime))

--------------------------------

3。记录显示登录日志实例

import time

def show_info():
    print('''输入提示数字,执行相应操作
0:退出
1:查看登录日志
    ''')

def write_loginfo(username):
    """
    将用户名和登录时间写入日志
    :param username: 用户名
    """
    with open('log.txt','a') as f:
        string = "用户名:{} 登录时间:{}\n".format(username ,time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
        f.write(string)

def read_loginfo():
    """
    读取日志
    """
    with open('log.txt','r') as f:
        while True:
            line = f.readline()
            if line == '':
                break  # 跳出循环
            print(line)  # 输出一行内容

if __name__ == "__main__":
    # 输入用户名
    username = input('请输入用户名:')
    # 检测用户名
    while len(username) < 2 :
        print('用户名长度应不少于2位')
        username = input('请输入用户名:')
    # 输入密码
    password = input('请输入密码:')
    # 检测密码
    while len(passw ord) < 6 :
        print('密码长度应不少于6位')
        password = input('请输入密码:')

    print('登录成功')
    write_loginfo(username)  # 写入日志
    show_info()              # 提示信息
    num = int(input('输入操作数字:')) # 输入数字
    while True:
        if num == 0:
            print('退出成功')
            break
        elif num == 1:
            print('查看登录日志')
            read_loginfo()
            show_info()
            num = int(input('输入操作数字:'))
        else:
            print('您输入的数字有误')
            show_info()
            num = int(input('输入操作数字:'))

------------------------------
3。模拟淘宝客服自动回复
 1 # 任务2:模拟淘宝客服自动回复
 2 
 3 def find_answer(question):
 4     with open('reply.txt','r') as f :
 5         while True:
 6             line=f.readline()
 7             if  not line:   #也可以为if  line==''
 8                 break
 9             keyword=line.split('|')[0]
10             reply=line.split('|')[1]
11             if keyword in question:
12                 return reply
13         return '对不起,没有你想要找的问题'
14          
15 if __name__ =='__main__':
16     question=input('请输入想要提问的内容:')
17     while True:
18         if question=='bye':
19             break
20         reply=find_answer(question)
21         if not reply:
22             question=input("小蜜不懂您在说什么,您可以问一些与订单、账户和支付相关的内容(退出请输入bye):")
23         else:
24             print(reply)
25             question=input("您可以问一些与订单、账户和支付相关的内容(退出请输入bye):")
26     print('谢谢,再见!')
27         

 

 

4。求最大公约数和最小公倍数 (辗转相除法)

最大公约数:指两个或多个整数共有约数中最大的一个

最小公倍数:两个或多个整数公有的倍数叫做它们的公倍数,其中除0以外最小的一个公倍数就叫做这几个整数的最小公倍数

二者关系:两个数之积=最小公倍数*最大公约数

 1 a=int(input('输入数字1:'))
 2 b=int(input('输入数字2:'))
 3 s=a*b
 4 while a%b!=0:
 5     a,b=b,(a%b)
 6     print(a)
 7     print(b)
 8 else:
 9     print(b,'is the maximum common divisor最大公约数')
10     print(s//b,'is the least common multiple,最小公倍数')

更相减损法

 1 a=int(input('please enter 1st num:'))
 2 b=int(input('please enter 2nd num:'))
 3 s=a*b
 4      
 5 while a!=b:
 6     if a>b:
 7         a-=b
 8     elif a<b:
 9         b-=a
10 else:
11     print(a,'is the maximum common divisor')
12     print(s//a,'is the least common multiple')
13  
14 #运行结果
15 please enter 1st num:40
16 please enter 2nd num:60
17 20 is the maximum common divisor
18 120 is the least common multiple
5。判断是否为闰年 (辗转相除法)
 1 # 判断是否为闰年
 2 while True:
 3     try:
 4         num=eval(input("请输入一个年份:"))
 5     except:
 6         print('输入错误年份')
 7         continue
 8     if (num %4==0 and num%100 !=0) or num %400==0:
 9         print(num,"是闰年")
10     else:
11         print(num,"不是闰年")

 

import calendar

year = int(input("请输入年份:"))
check_year=calendar.isleap(year)
if check_year == True:
    print ("闰年")
else:
    print ("平年")
6。Python统计字符串中数字,字母,汉字的个数
 1 import re
 2 str_test='abcdefgHABC123456中华民族'
 3  
 4 #把正则表达式编译成对象,如果经常使用该对象,此种方式可提高一定效率
 5 num_regex = re.compile(r'[0-9]')
 6 zimu_regex = re.compile(r'[a-zA-z]')
 7 hanzi_regex = re.compile(r'[\u4E00-\u9FA5]')
 8 
 9 print('输入字符串:',str_test)
10 #findall获取字符串中所有匹配的字符
11 num_list = num_regex.findall(str_test)
12 print('包含的数字:',num_list)
13 zimu_list = zimu_regex.findall(str_test)
14 print('包含的字母:',zimu_list)
15 hanzi_list = hanzi_regex.findall(str_test)
16 print('包含的汉字:',hanzi_list)

 #羊车门问题

 1 import random as r
 2 
 3 #总次数
 4 total=1000000 #1000,1W,10W,100W
 5 #换与不换的获胜次数
 6 win1=0
 7 win2=0
 8 
 9 for i in range(total):
10     #模拟选择过程
11     man=r.randint(1,3)
12     car=r.randint(1,3)
13     #结果:一开始为车门,不换+1.
14     #       否则则一开始为羊门,换+1.
15     if man==car:
16         win1+=1
17     else:
18         win2+=1
19 
20 print("在{}次实验中:".format(total))
21 print("若不更改门,获胜概率为{:.3}%.".format((win1/total)*100))
22 print("若更改门,获胜概率为{:.3}%.".format((win2/total)*100))
 1 import random
 2 x=random.randint(5000,10000)
 3 print(x)
 4 change=0
 5 nochange=0
 6 for i in range(1,x+1):
 7   a=random.randrange(1,4)
 8   b=random.randrange(1,4)
 9   if a==b:
10     nochange=nochange+1
11   else:
12     change=change+1
13 print("不更改选择得到汽车的概率为{:.2f}".format(nochange/x))
14 
15 print("更改选择得到汽车的概率为{:.2f}".format(change/x))

 

 

转载于:https://www.cnblogs.com/huigebj/p/11295202.html

<think>好的,用户想要找Python爬虫的示例代码。首先,我需要回忆一下之前提供的引用内容,看看有哪些相关的资料。引用[1]提到Python爬虫常用的库,比如requests、BeautifulSoup和Scrapy。引用[3]有一个简单的示例,使用requests库获取百度页面并打印信息。引用[2]则提到urllib2库的示例,不过现在可能更推荐使用requests代替urllib2,因为requests更简单易用。 接下来,我应该整理这些信息,分步骤展示不同的示例。先从最简单的开始,比如引用[3]中的代码,用requests获取网页内容。然后,可能需要一个使用BeautifulSoup解析HTML的例子,这样用户可以看到如何提取具体的数据。再进一步,可以加入Scrapy框架的简单示例,因为引用[1]提到了Scrapy作为完整的框架。 需要注意的是,用户可能对不同的库不太熟悉,所以每个示例应该尽量简洁,并附上解释。比如,解释每个步骤的作用,比如发送请求、处理响应、解析内容等。同时,提醒用户遵守网站的robots.txt,避免过于频繁的请求,防止被封IP。 另外,用户可能想知道更多相关的资源或扩展,比如如何保存数据到文件,或者处理动态加载的内容。这时候可以建议学习Selenium或Scrapy,如引用中提到的。同时,引用提供的资料可以作为进一步学习的参考,比如引用[2]和[3]中的实例代码。 最后,确保回答结构清晰,分点说明每个示例,并在最后提供相关问题,帮助用户深入学习和解决问题。检查代码是否正确,比如是否正确的缩进,库是否正确导入,避免语法错误。同时,按照用户要求,数学公式用$...$,但在这个问题中可能用不上,但需要确保其他格式正确,如代码块使用反引号包裹,引用标识正确添加。</think>以下是一个使用Python实现网络爬虫的完整示例,包含基本功能和代码解析: ### 1. 基础网页抓取示例 ```python import requests # 发送HTTP GET请求 response = requests.get("https://www.example.com") response.encoding = 'utf-8' # 设置编码格式 print(f"状态码: {response.status_code}") # 输出状态码 print(response.text) # 输出网页内容 ``` *代码说明*:通过requests库获取网页内容,显示HTTP状态码和页面HTML源码[^3] ### 2. 网页解析示例(使用BeautifulSoup) ```python from bs4 import BeautifulSoup import requests # 获取网页内容 url = "https://books.toscrape.com/" response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') # 提取图书标题 book_titles = [] for article in soup.find_all('article', class_='product_pod'): title = article.h3.a['title'] book_titles.append(title) print("前5本图书标题:") print('\n'.join(book_titles[:5])) ``` *代码说明*:使用BeautifulSoup解析HTML文档,提取特定CSS类中的图书标题信息[^1] ### 3. 完整爬虫示例(含数据存储) ```python import requests from bs4 import BeautifulSoup import csv def crawl_quotes(): url = "http://quotes.toscrape.com" response = requests.get(url) soup = BeautifulSoup(response.text, 'lxml') with open('quotes.csv', 'w', newline='', encoding='utf-8') as f: writer = csv.writer(f) writer.writerow(['内容', '作者', '标签']) for quote in soup.find_all('div', class_='quote'): text = quote.find('span', class_='text').text author = quote.find('small', class_='author').text tags = [tag.text for tag in quote.find_all('a', class_='tag')] writer.writerow([text, author, ','.join(tags)]) if __name__ == '__main__': crawl_quotes() print("数据已保存至quotes.csv") ``` *代码说明*:完整爬虫流程包含请求发送、页面解析和数据存储功能[^2] **注意事项**: 1. 遵守网站的`robots.txt`协议 2. 添加适当的请求头(User-Agent) 3. 设置请求间隔(建议2-5秒) 4. 异常处理(网络超时、页面解析失败等)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值