第7章

7.1
def convert_to_uppercase():
file_path = input("请输入python源文件路径:")
try:
with open(file_path,'r',encoding='utf-8') as f:
content = f.read()
new_content = ''
for char in content:
if char.isalpha() and not char.isupper():
new_content += char.upper()
else:
new_content += char
output_path = file_path.rsplit('.',1)[0] + '_modified.py'
with open(output_path,'w',encoding='utf-8') as f:
f.write(new_content)
print(f"转换后的文件已保存为{output_path}")
except FileNotFoundError:
print("指定文件不存在,请检查路径")

if name == "main":
convert_to_uppercase()


7.2
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt

def get_stopwords():
stopwords_path = "D:\CY的Python课作业\stopwords.txt"
with open(stopwords_path,'r',encoding='GBK') as f:
stopwords = [line.strip() for line in f.readlines()]
return set(stopwords)

def read_report():
report_path = "D:\CY的Python课作业\2023年中央一号文件(全文).txt"
with open(report_path,'r',encoding='utf-8') as f:
report_text = f.read()
return report_text

def process_text(text,stopwords):
words = jieba.lcut(text)
word_counts = {}
for word in words:
if word not in stopwords and len(word) > 1:
word_counts[word] = word_counts.get(word,0) + 1
return word_counts

def generate_wordcloud(word_counts):
sorted_word_counts = sorted(word_counts.items(),key=lambda x: x[1],reverse=True)
top_100_words = dict(sorted_word_counts[:100])
wc = WordCloud(font_path='simhei.ttf', background_color = 'white',width = 800,height=600)
wc.generate_from_frequencies(top_100_words)
plt.figure(figsize=(10, 8))
plt.imshow(wc,interpolation='bilinear')
plt.axis('off')
plt.show()

if name=="main":
stopwords = get_stopwords()
report_txt = read_report()
word_counts = proccess_text(report_txt,stopwords)
generate_wordcloud(word_counts)

7.3
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()

7.4
import jieba
import imageio
from wordcloud import WordCloud
import matplotlib.pyplot as plt

def get_mask():
logo_path = "D:\CY的Python课作业\logo.PNG"
return imageio.imread(logo_path)

def process_text(text):
words = jieba.lcut(text)
word_counts = {}
for word in words:
if len(word) > 1:
word_counts[word] = word_counts.get(word,0) + 1
return word_counts
def generate_wordcloud(word_counts,mask):
wc = WordCloud(font_path='simhei.ttf',background_color='white',mask=mask)
wc.generate_from_frequencies(word_counts)
plt.figure(figsize=(10, 8))
plt.imshow(wc,interpolation='bilinear')
plt.axis('off')
plt.show()

if name=="main":
mask = get_mask()
poem = "君不见,黄河之水天上来,奔流到海不复回。君不见,高堂明镜悲白发,朝如青丝暮成雪。人生得意须尽欢,莫使金樽空对月。
天生我材必有用,千金散尽还复来。烹羊宰牛且为乐,会须一饮三百杯。岑夫子,丹丘生,将进酒,杯莫停。与君歌一曲,请君为我倾耳听。
钟鼓馔玉不足贵,但愿长醉不复醒。古来圣贤皆寂寞,惟有饮者留其名。陈王昔时宴平乐,斗酒十千恣欢谑。主人何为言少钱,径须沽取对君酌。
五花马,千金裘,呼儿将出换美酒,与尔同销万古愁。"
word_counts = process_text(poem)
generate_wordcloud(word_counts,mask)

7.5
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()

posted @ 2025-05-18 15:15  piuky  阅读(58)  评论(0)    收藏  举报