第十二周
def rewrite_py_file(file_path):
try:
with open(file_path, 'r', encoding='utf - 8') as f:
content = f.read()
new_content = ""
i = 0
while i < len(content):
char = content[i]
if char.islower() and char not in ["def", "class", "if", "else", "for", "while", "import", "from", "in", "and", "or", "not", "True", "False", "None"]:
new_content += char.upper()
else:
new_content += char
i += 1
new_file_path = file_path.rsplit('.', 1)[0] + '_modified.py'
with open(new_file_path, 'w', encoding='utf - 8') as f:
f.write(new_content)
print(f"文件已成功改写并保存为{new_file_path}")
except FileNotFoundError:
print(f"文件{file_path}未找到")
if name == "main":
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)
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")
file_path = input("请输入要改写的Python源文件路径: ")
rewrite_py_file(file_path)
import matplotlib.pyplot as plt
import numpy as np
def draw_circular_trajectory():
import jieba
from wordcloud import WordCloud
import numpy as np
from PIL import Image
import requests
from bs4 import BeautifulSoup
def get_poem_text():
url = "诗词网址"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
poem_text = ""
for p in soup.find_all('div', class_='poem_content'): # 假设诗词内容在class为poem_content的div中
poem_text += p.get_text()
return poem_text
def generate_logo_wordcloud():
poem_text = get_poem_text()
words = jieba.lcut(poem_text)
words_str = " ".join(words)
logo_mask = np.array(Image.open("school_logo.png"))
wordcloud = WordCloud(font_path='msyh.ttc', mask=logo_mask, background_color='white').generate(words_str)
wordcloud.to_file("logo_wordcloud.png")
print("Logo词云已生成并保存为logo_wordcloud.png")
if name == "main":
generate_logo_wordcloud()
center_x = 0
center_y = 0
radius = 1
theta = np.linspace(0, 2 * np.pi, 100)
x = center_x + radius * np.cos(theta)
y = center_y + radius * np.sin(theta)
plt.plot(x, y)
plt.axis('equal')
plt.title('圆形轨迹')
plt.show()
if name == "main":
draw_circular_trajectory()
import turtle
def create_circle_date(center_x,center_y,radius,num_segments):
circle_date = {"center_x": center_x,"center_y": center_y,"radius":radius,"num_segments":num_segments}
return circle_date
def draw_circle_trajectory(circle_date):
center_x = circle_date["center_x"]
center_y = circle_date["center_y"]
radius = circle_date["radius"]
num_segments = circle_date["num_segments"]
turtle.penup()
turtle.goto(center_x + radius,center_y)
turtle.pendown()
angle = 360 / num_segments
for _ in range(num_segments):
turtle.circle(radius,angle)
if name=="main":
circle_date = create_circle_date(0,0,100,36)
draw_circle_trajectory(circle_date)
turtle.done()
def add_word(dictionary,word,meaning):
if word in dictionary:
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 main():
dictionary = {}
file_path = "D:\CY的Python课作业\dictionary.txt"
try:
with open(file_path,'r',encoding='GBK',errors='ignore') as f:
for line in f:
parts = line.strip().split(' ')
if len(parts) >= 2:
meaning = ' '.join(parts[1:])
dictionary[parts[0]] = meaning
except FileNotFoundError:
with open(file_path,'w',encoding='utf-8') as f:
pass
while True:
print("请选择操作:")
print("1.添加单词")
print("2.查询单词")
print("3.退出")
choice = input("请输入你的选择(1/2/3)
if choice == '1':
word = input("请输入英文单词:")
meaning = input("请输入中文释义:")
add_word(dictionary,word,meaning)
with open (file_path,'a',encoding='utf-8')as f:
f.write(f"{word} {meaning}\n")
elif choice == '2':
word = input("请输入要查询的单词:")
query_word(dictionary,word)
elif choice == '3':
print("退出程序")
break
else:
print("输入有误,请重新输入")
if name == "main":
main()
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()