import random
import pymysql
def creat_num(num,long):
"""
num: 激活码的个数
long:激活码的位数
"""
str = 'qwertyuiopasdfghjklzxcvbnm1234567890'
b = []
for i in range(num):
a = ''
for j in range(long):
a += random.choice(str)
b.append(a)
return b
def InsertIntoMysql(codelist):
# 打开数据库连接
db = pymysql.connect(host='127.0.0.1',user='root',passwd='919824467',db='mysql')
# 使用 cursor() 方法创建一个游标对象 cursor
cur = db.cursor()
#数据库语句
cur.execute('CREATE DATABASE IF NOT EXISTS code')
cur.execute('USE code')
cur.execute('''CREATE TABLE IF NOT EXISTS num(
id INT NOT NULL AUTO_INCREMENT,
code VARCHAR(32) NOT NULL,
PRIMARY KEY(id) )''')
for num in codelist:
cur.execute('INSERT INTO num(code) VALUES(%s)',(num))
cur.connection.commit()
db.close()
if __name__ == "__main__":
InsertIntoMysql(creat_num(200,10))
第 0004 题: 任一个英文的纯文本文件,统计其中的单词出现的个数。
[Python] 纯文本查看复制代码
# encoding: utf-8
import collections
import re
def countWords(input_filename, output_filename):
try:
with open(input_filename, 'r', encoding='utf-8') as fp:
text = fp.read()
# 使用正则表达式去除标点符号,并将文本转换为小写
cleaned_text = re.sub(r'[^\w\s]', '', text.lower())
# 使用正则表达式分割单词
words = re.findall(r'\b\w+\b', cleaned_text)
word_counts = collections.Counter(words)
with open(output_filename, 'w', encoding='utf-8') as result_file:
for key, value in word_counts.items():
result_file.write(key + ':' + str(value) + '\n')
print(f"单词统计结果已写入到 {output_filename}")
except FileNotFoundError:
print(f"文件 {input_filename} 不存在,请检查文件名和路径是否正确。")
except Exception as e:
print(f"发生错误:{e}")
if __name__ == "__main__":
input_filename = input('input a filename:')
output_filename = input('output filename is:')
countWords(input_filename, output_filename)
import os, re
def mainKeywords(dirPath):
blank, comments, codelines, totalines, count, temp = 0, 0, 0, 0, 0, 0
f_list = os.listdir(dirPath)
for i in f_list:
if os.path.splitext(i)[1] == '.py':
file_path = os.path.join(dirPath, i)
print(f">Processing file: {file_path}")
with open(file_path, 'r', encoding='utf-8') as fp:
multiline_comment = False
for line in fp:
totalines += 1
if multiline_comment:
if '"""' in line or "'''" in line:
if line.strip().endswith('"""') or line.strip().endswith("'''"):
multiline_comment = False
comments += 1
elif line.strip().startswith('#'):
comments += 1
elif '"""' in line or "'''" in line:
if line.strip().startswith('"""') or line.strip().startswith("'''"):
multiline_comment = True
comments += 1
elif line.strip():
codelines += 1
else:
blank += 1
print('The total number of lines is : ' + str(totalines))
print('The number of comments is : ' + str(comments))
print('The number of code lines is : ' + str(codelines))
print('The number of blank lines is : ' + str(blank))
if __name__ == "__main__":
mainKeywords('.')
第 0008 题: 一个HTML文件,找出里面的正文。
第 0009 题: 一个HTML文件,找出里面的链接。
[Python] 纯文本查看复制代码
from bs4 import BeautifulSoup
def searchBody(path):
with open(path,encoding='utf-8') as fp:
text = BeautifulSoup(fp, 'lxml')
urls = text.findAll('a')
for u in urls:
print(u['href'])
content = text.get_text().strip('\n')
return content
if __name__ == "__main__":
print(searchBody('text.html'))
第 0010 题: 使用 Python 生成类似于下图中的字母验证码图片
[Python] 纯文本查看复制代码
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
# 随机字母:
def rndChar():
return chr(random.randint(65, 90))
# 随机颜色1:
def rndColor():
return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))
# 随机颜色2:
def rndColor2():
return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
def captchaImage():
# 240 x 60:
width = 240
height = 60
image = Image.new('RGB', (width, height), (255, 255, 255))
# 创建Font对象:
font = ImageFont.truetype('SimHei.ttf', 36)
# 创建Draw对象:
draw = ImageDraw.Draw(image)
# 填充每个像素:
for x in range(width):
for y in range(height):
draw.point((x, y), fill=rndColor())
# 输出文字:
for t in range(4):
draw.text((60 * t + 10, 10), rndChar(), font=font, fill=rndColor2())
# 模糊:
image = image.filter(ImageFilter.BLUR)
# 保存图片
image.save('code.jpg', 'jpeg');
# 显示图片(注意:在Jupyter Notebook等环境中可能需要不同的显示方法)
image.show()
if __name__ == "__main__":
captchaImage()