P264习题
7.1
import tokenize
import keyword
from io import BytesIO
def convert_python_file(source_path, target_path):
with open(source_path, 'rb') as file:
tokens = list(tokenize.tokenize(file.readline))
new_tokens = []
for tok in tokens:
if tok.type == tokenize.NAME and tok.string in keyword.kwlist:
new_tokens.append(tok)
elif tok.type == tokenize.NAME:
new_str = tok.string.upper()
new_tok = tokenize.TokenInfo(
type=tok.type,
string=new_str,
start=tok.start,
end=tok.end,
line=tok.line
)
new_tokens.append(new_tok)
else:
new_tokens.append(tok)
new_code = tokenize.untokenize(new_tokens).decode('utf-8')
7.2
def process_text(input_file, output_image, max_words=100, font_path='SimHei.ttf'):
with open(input_file, 'r', encoding='utf-8') as f:
text = f.read()
words = jieba.lcut(text)
stopwords = set(['的', '了', '是', '在', '和', '就', '都', '而', '及', '等', '这个', '可以'])
filtered_words = [
word for word in words
if len(word) > 1
and word not in stopwords
and '\u4e00' <= word <= '\u9fff'
]
word_counts = Counter(filtered_words)
top_words = word_counts.most_common(max_words)
wc = WordCloud(
font_path=font_path,
width=800,
height=600,
background_color='white',
max_words=max_words
)
wc.generate_from_frequencies(dict(top_words))
plt.figure(figsize=(10, 8))
plt.imshow(wc, interpolation='bilinear')
plt.axis('off')
plt.savefig(output_image, bbox_inches='tight', dpi=300)
plt.close()
if name == 'main':
process_text(
input_file='中央文件.txt',
output_image='wordcloud.png',
max_words=100,
font_path='SimHei.ttf'
)
with open(target_path, 'w', encoding='utf-8') as file:
file.write(new_code)
7.3
CircleTrackDraw.py
import turtle as t
def setup_canvas():
t.title('圆形轨迹绘制引擎')
t.setup(800, 600)
t.speed(0)
t.hideturtle()
def parse_data(file_path):
commands = []
with open(file_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if not line or line.startswith('#'):
continue
params = list(map(eval, line.split(',')))
commands.append({
'radius': params[0],
'extent': params[1],
'color': (params[2] / 255, params[3] / 255, params[4] / 255)
})
return commands
def draw_circle_tracks(commands):
t.penup()
t.goto(0, -200)
t.setheading(0)
t.pendown()
for cmd in commands:
t.pencolor(cmd['color'])
t.circle(cmd['radius'], cmd['extent'])
if name == 'main':
setup_canvas()
drawing_commands = parse_data("circle_data.txt")
draw_circle_tracks(drawing_commands)
t.done()
7.4
import numpy as np
from PIL import Image
import jieba
from wordcloud import WordCloud, ImageColorGenerator
import matplotlib.pyplot as plt
mask = np.array(Image.open("logo.png"))
text = """天若有情天亦老,人间正道是沧桑。"""
words = jieba.lcut(text)
word_counts = {word: words.count(word) for word in set(words) if len(word) > 1}
wc = WordCloud(
font_path="SimHei.ttf", # 需指定中文字体
mask=mask,
background_color="white",
max_words=100,
contour_width=3,
contour_color='#003366' # 可匹配校徽主色调
)
wc.generate_from_frequencies(word_counts)
image_colors = ImageColorGenerator(mask)
wc.recolor(color_func=image_colors)
plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
plt.savefig("logo_wordcloud.png", dpi=300, bbox_inches='tight')
7.5
import os
def load_dictionary(file_path):
dictionary = {}
if os.path.exists(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line:
parts = line.split(maxsplit=1)
if len(parts) == 2:
en, cn = parts
dictionary[en.lower()] = cn
return dictionary
def save_word(file_path, en_word, cn_word):
with open(file_path, 'a', encoding='utf-8') as f:
f.write(f"{en_word} {cn_word}\n")
def add_word(dictionary, file_path):
en_word = input("请输入要添加的英文单词:").strip().lower()
cn_word = input("请输入对应的中文释义:").strip()
if not en_word or not cn_word:
print("输入不能为空!")
return
if en_word in dictionary:
print("该单词已添加到字典库")
else:
dictionary[en_word] = cn_word
save_word(file_path, en_word, cn_word)
print("添加成功!")
def search_word(dictionary):
en_word = input("请输入要查询的英文单词:").strip().lower()
result = dictionary.get(en_word)
if result:
print(f"中文释义:{result}")
else:
print("字典库中未找到这个单词")
def main():
file_path = "dictionary.txt"
dictionary = load_dictionary(file_path)
if not os.path.exists(file_path):
open(file_path, 'w', encoding='utf-8').close()
while True:
print("\n===== 英文学习词典 =====")
print("1. 添加单词")
print("2. 查询单词")
print("3. 退出系统")
choice = input("请输入选项数字:").strip()
if choice == '1':
add_word(dictionary, file_path)
elif choice == '2':
search_word(dictionary)
elif choice == '3':
print("感谢使用,再见!")
break
else:
print("输入有误,请重新输入")
if name == "main":
main()
7.6
import os
def load_dictionary(file_path):
dictionary = {}
if os.path.exists(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line:
parts = line.split(maxsplit=1)
if len(parts) == 2:
en, cn_str = parts
cn_list = [c.strip() for c in cn_str.split(',') if c.strip()]
dictionary[en.lower()] = cn_list
return dictionary
def save_word(file_path, en_word, cn_words):
with open(file_path, 'a', encoding='utf-8') as f:
cn_str = ','.join(cn_words)
f.write(f"{en_word} {cn_str}\n")
def add_word(dictionary, file_path):
en_word = input("请输入要添加的英文单词:").strip().lower()
if not en_word:
print("英文单词不能为空!")
return
if en_word in dictionary:
print("该单词已添加到字典库")
return
cn_input = input("请输入对应的中文释义(多个用英文逗号分隔):").strip()
cn_words = [c.strip() for c in cn_input.replace(',', ',').split(',') if c.strip()]
if not cn_words:
print("中文释义不能为空!")
return
dictionary[en_word] = cn_words
save_word(file_path, en_word, cn_words)
print("添加成功!")
def search_word(dictionary):
en_word = input("请输入要查询的英文单词:").strip().lower()
result = dictionary.get(en_word)
if result:
print(f"中文释义:{', '.join(result)}")
else:
print("字典库中未找到这个单词")
def main():
file_path = "dictionary.txt"
dictionary = load_dictionary(file_path)
if not os.path.exists(file_path):
open(file_path, 'w', encoding='utf-8').close()
while True:
print("\n===== 英文学习词典 =====")
print("1. 添加单词")
print("2. 查询单词")
print("3. 退出系统")
choice = input("请输入选项数字:").strip()
if choice == '1':
add_word(dictionary, file_path)
elif choice == '2':
search_word(dictionary)
elif choice == '3':
print("感谢使用,再见!")
break
else:
print("输入有误,请重新输入")
if name == "main":
main()