python经典题分享
本帖最后由 科迈罗 于 2024-6-26 21:57 编辑这个GitHub原地址https://github.com/Yixiaohan/show-me-the-code
算是比较老的25道题了,今天个人先整理一下前10道题
第 0000 题: 将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果。 类似于图中效果
from PIL import Image, ImageDraw, ImageFont
# PIL https://pillow.readthedocs.org/
def add_num(img):
# 创建一个绘画对象针对参数开始绘画
draw = ImageDraw.Draw(img)
# 加载TrueType或OpenType字体文件,并创建一个字体对象。
myfont = ImageFont.truetype('./SimHei.ttf', size = 50)
# 加载字体颜色
fillcolor = "#008c8c"
# 加载图片宽和高
width, height = img.size
# 在图片上画上字,坐标原点为图片左上角
draw.text((width-20, 0), '0', font = myfont, fill = fillcolor)
# 保存图片
img.save('./result.jpg','jpeg')
return 0
if __name__ == "__main__":
image = Image.open('./image.jpg')
print(image.format,image.size,image.mode)
add_num(image)
第 0001 题: 做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)?
第 0002 题: 将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。
第 0003 题: 将 0001 题生成的 200 个激活码(或者优惠券)保存到 Redis 非关系型数据库中。
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 题: 任一个英文的纯文本文件,统计其中的单词出现的个数。
# 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)
第 0005 题: 你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone5 分辨率的大小。
from PIL import Image
import os
def resize(dirPath, size_x, size_y):
"""
dirPath:目标文件夹的路径
size_x:宽
size_y:高
"""
f_list = os.listdir(dirPath)
for i in f_list:
if os.path.splitext(i) == '.jpg':
img = Image.open(dirPath + '/' + i)
img.thumbnail((size_x, size_y))
img.save(dirPath + '/' + i)
print(f"Resized: {i}")
if __name__ == "__main__":
resize('./image', 1136, 640)
第 0006 题: 你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词。
# encoding: utf-8
import collections
import os.path
import re
from string import punctuation
# 常见的英文停用词列表
STOPWORDS = set(['the', 'her', 'his', 'and', 'she', 'it', 'to', 'a', 'an', 'in', 'on', 'is', 'its', 'that', 'for', 'are', 'was', 'were', 'will', 'be', 'have', 'has', 'do', 'does', 'did', 'at', 'by', 'from', 'with', 'as', 'of', 'this', 'these', 'those', 'they', 'their', 'them', 'or', 'but', 'if', 'then', 'so', 'all', 'any', 'both', 'each', 'few', 'more', 'most', 'other', 'some', 'such', 'no', 'nor', 'not', 'only', 'own', 'same', 'than', 'too', 'very', 'can', 'may', 'must', 'should', 'would', 'am', 'could', 'might', 'shall', 'will', 'would', 'about', 'after', 'again', 'also', 'an', 'another', 'any', 'because', 'before', 'between', 'both', 'but', 'by', 'came', 'can', 'come', 'could', 'during', 'each', 'few', 'for', 'from', 'further', 'had', 'has', 'have', 'he', "he's", 'her', 'here', 'hers', 'herself', 'him', 'himself', 'his', 'how', 'in', 'into', 'is', 'it', "it's", 'its', 'itself', 'just', 'like', 'make', 'many', 'me', 'might', 'more', 'most', 'much', 'must', 'my', 'myself', 'never', 'now', 'o', 'of', 'off', 'on', 'once', 'only', 'or', 'other', 'our', 'ours', 'ourselves', 'out', 'over', 'own', 'same', 'she', "she's", 'should', 'so', 'some', 'such', 'than', 'that', 'the', 'their', 'theirs', 'them', 'themselves', 'these', 'they', "they're", 'this', 'those', 'through', 'to', 'too', 'under', 'until', 'up', 'very', 'was', 'were', 'what', 'when', 'where', 'which', 'while', 'who', 'whom', 'why', 'with', 'would', 'you', 'your', 'yours', 'yourself', 'yourselves'])
def judgeit(words):
for i in range(6):
if len(words) > 2 and words != 'the' and words != 'her' and words !='his' and words != 'and' and words != 'she':
returnwords
return words
## 使用正则表达式进行分词,并去除标点符号和转换为小写
#words = re.findall(r'\b\w+\b', text.lower())
## 去除停用词
#words =
## 统计词频
#word_counts = collections.Counter(words)
## 返回频率最高的词
#return word_counts.most_common(1)
def mainKeywords(dirPath):
f_list = os.listdir(dirPath)
for i in f_list:
if os.path.splitext(i) == '.txt':
print(f'the keywords of {i} is:')
with open(i, 'r', encoding='utf-8') as fp:
str1 = fp.read().split(' ')
b = collections.Counter(str1)
keywords = sorted(b, key=lambda x: b,reverse = True)
print(judgeit(keywords))
if __name__ == "__main__":
mainKeywords('./')
第 0007 题: 有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来。
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) == '.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文件,找出里面的链接。
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 生成类似于下图中的字母验证码图片
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()
验证码的那种字体变形没有太整明白,试了试调整画布姿态粘贴出来from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
# 随机字母:
def rndChar():
return chr(random.randint(65, 90))
# 随机颜色1:
def rndColor():
return (random.randint(64, 200), random.randint(64, 200), random.randint(64, 200))
# 随机颜色2:
def rndColor2():
return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
def captchaImage():
# 背景图
size = 5
width, height = 240, 60
image = Image.new('RGB', (width, height), (255, 255, 255))
draw = ImageDraw.Draw(image)
# 字符间距和字体大小
char_spacing = random.randint(8, 12)
font_size = random.randint(8, 14)*4
# font = ImageFont.truetype('SimHei.ttf', font_size)
font = ImageFont.truetype('SourceHanSansSC-Bold.otf', font_size)
# 填充每个像素:
for x in range(width//size):
for y in range(height//size):
# 绘制像素点,随机填充颜色
# draw.point((x, y), fill=rndColor())
# 绘制10x10的矩形块,填充随机颜色
draw.rectangle([(x*size, y*size), (x*size + size, y*size + size)], fill=rndColor())
# 输出文字:
# 计算每个字符的起始x坐标
start_x = (width - char_spacing * 3 - font_size * 4) // 2
# 生成四个字符并分别处理
for i in range(4):
# 为每个字符创建一个小的text_image
text_image = Image.new('RGBA', (font_size + 2 * char_spacing, font_size + 2 * char_spacing), (0, 0, 0, 0))
text_draw = ImageDraw.Draw(text_image)
# 绘制字符(稍微偏移以避免裁剪到边缘)
text_x = char_spacing
text_y = (text_image.height - font_size) // 2
text_draw.text((text_x, text_y-random.randint(8, 12)), rndChar(), font=font, fill=rndColor2())
# 旋转文本图像
angle = random.randint(-9, 9)*5# 限制旋转角度
rotated_text_image = text_image.rotate(angle, expand=True)
# 计算粘贴位置
rotated_text_width, rotated_text_height = rotated_text_image.size
x = start_x + i * (font_size + char_spacing) + (font_size - rotated_text_width) // 2
y = (height - rotated_text_height) // 2
# 粘贴旋转后的文本到背景图像
image.paste(rotated_text_image, (x, y), rotated_text_image)
# 模糊:
image = image.filter(ImageFilter.GaussianBlur(radius=0.5))
# 保存图片
image.save('code.png', 'PNG')
# 显示图片(注意:在Jupyter Notebook等环境中可能需要不同的显示方法)
image.show()
if __name__ == "__main__":
captchaImage() 最后一题怎么才能做到字母朝左或者朝右倾斜,再在图片中加一些混乱的线条阻挡,之前就好奇这种是怎么做到的 先评论收藏,然后慢慢学习。 先插个眼 最后一题实用性高,后端调用这个脚本生成验证码,本地存一份,图片返回给前端展示 谢谢分享,初学者值得看看
谢谢分享,先插眼收藏。{:1_893:} 这是好东西啊,收藏了 先收藏再学习 都这么难的啊…… 谢谢分享,值得收藏