第12周
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') with open(target_path, 'w', encoding='utf-8') as file: file.write(new_code)
7.2
import jieba import wordcloud import numpy as np from PIL import Image fname = "第十周\三国演义.txt" with open(fname, "r", encoding="utf-8") as f: ls = jieba.lcut(f.read()) for item in reversed(ls): if len(item) == 1: ls.remove(item)
7.3
x, y = np.ogrid[:300, :300] mask = (x - 150) ** 2 + (y - 150) ** 2 > 130 ** 2 mask = 255 * mask.astype(int) w = wordcloud.WordCloud(font_path="msyh.ttc",width=1000, height=700,background_color="white",font_step=1,mask=mask) w.generate(" ".join(ls)) w.to_file("output.png") import turtle as t t.title("自动轨迹绘制") t.setup(1000, 800, 0, 0) t.pencolor("red") t.pensize(5)
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 add_word(dictionary, word, meaning):
if word in dictionary:
dictionary[word] += f", {meaning}"
print(f"单词{word}已添加新释义到字典库")
else:
dictionary[word] = meaning
print(f"单词{word}已成功添加到字典库")
def query_word(dictionary, word):
if word in dictionary:
print(f"{word}: {dictionary[word]}")
else:
print(f"字典库中未找到这个单词{word}")
def save_dictionary(dictionary, file_path):
with open(file_path, 'w', encoding='utf - 8') as f:
for word, meaning in dictionary.items():
f.write(f"{word} {meaning}\n")
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:
parts = line.strip().split(maxsplit=1)
if len(parts) == 2:
dictionary[parts[0]] = parts[1]
return dictionary
def main():
file_path = "dictionary.txt"
dictionary = load_dictionary(file_path)
while True:
choice = input("请选择操作:1. 添加单词 2. 查询单词 3. 退出\n")
if choice == "1":
word = input("请输入英文单词:")
meaning = input("请输入中文释义:")
add_word(dictionary, word, meaning)
save_dictionary(dictionary, file_path)
elif choice == "2":
word = input("请输入要查询的英文单词:")
query_word(dictionary, word)
elif choice == "3":
print("退出程序")
break
else:
print("输入有误")
if name == "main":
main()`
浙公网安备 33010602011771号