book7

7.1
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":
file_path = input("请输入要改写的Python源文件路径: ")
rewrite_py_file(file_path)

7.2
import jieba
from wordcloud import WordCloud
import requests
from bs4 import BeautifulSoup

def get_gov_report_text():
# 这里假设从政府官网获取报告,实际需根据真实网址调整
url = "政府工作报告网址"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
text = ""
for p in soup.find_all('p'):
text += p.get_text()
return text

def generate_gov_wordcloud():
text = get_gov_report_text()
words = jieba.lcut(text)
# 去除非语义词语(简单示例,实际需更完善词表 )
stopwords = ["的", "了", "是", "和", "在", "等"]
filtered_words = [word for word in words if word not in stopwords]
words_str = " ".join(filtered_words)
wordcloud = WordCloud(font_path='msyh.ttc', max_words=100, background_color='white').generate(words_str)
wordcloud.to_file("gov_wordcloud.png")
print("词云已生成并保存为gov_wordcloud.png")

if name == "main":
generate_gov_wordcloud()

7.3
import matplotlib.pyplot as plt
import numpy as np

def draw_circular_trajectory():
# 圆心坐标
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()

7.4
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图片
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()

7.5
import os

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

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

posted @ 2025-05-16 20:56  荔枝Y  阅读(41)  评论(0)    收藏  举报