困难代码7.0

源代码改写

import keyword
import re
import sys

def transform_python_file(input_file, output_file):
reserved_words = set(keyword.kwlist)
with open(input_file, 'r', encoding='utf-8') as f:
content = f.read()
transformed = []
pos = 0

for match in re.finditer(r'(\'[^\']*\'|\"[^\"]*\"|\'\'\'.*?\'\'\'|\"\"\".*?\"\"\"|#[^\n]*|\b[a-zA-Z_][a-zA-Z0-9_]*\b)', content, re.DOTALL):
    transformed.append(content[pos:match.start()].upper())
    matched_text = match.group()
    if matched_text[0] in ('\'', '"'):
        transformed.append(matched_text)
    elif matched_text.startswith('#'):
        transformed.append(matched_text)
    else:
        if matched_text in reserved_words:
            transformed.append(matched_text)
        else:
            transformed.append(matched_text.upper())
    pos = match.end()
transformed.append(content[pos:].upper())
result = ''.join(transformed)
with open(output_file, 'w', encoding='utf-8') as f:
    f.write(result)

if name == "main":
if len(sys.argv) != 3:
print("使用方法: python transform.py 输入文件.py 输出文件.py")
sys.exit(1)

input_file = sys.argv[1]
output_file = sys.argv[2]

try:
    transform_python_file(input_file, output_file)
    print(f"转换完成,结果已保存到 {output_file}")
except Exception as e:
    print(f"转换过程中发生错误: {e}")
    sys.exit(1)

政府工作报告词云

import requests
import jieba
import jieba.analyse
from wordcloud import WordCloud
import matplotlib.pyplot as plt
from collections import Counter
import re

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

custom_stopwords = set([
'的', '和', '在', '了', '是', '我', '有', '要', '对', '为', '等', '这', '就',
'也', '会', '到', '与', '上', '年', '以', '中', '不', '都', '将', '并', '或',
'一个', '一些', '可以', '我们', '他们', '它们', '这个', '这些', '那些',
'没有', '不是', '非常', '更加', '就是', '这样', '那样', '因为', '所以',
'但是', '然后', '而且', '如果', '虽然', '为了', '通过', '作为', '以及',
'需要', '继续', '进一步', '不断', '必须', '应该', '可能', '已经', '正在',
'成为', '其他', '任何', '进行', '发展', '建设', '国家', '政府', '工作',
'报告', '今年', '2023', '2024', '2025', '推进', '实施', '提高', '加强',
'完善', '加快', '促进', '推动', '实现', '开展', '坚持', '深化', '全面',
'持续', '加大', '做好', '落实', '问题', '方面', '领域', '水平', '能力',
'体系', '机制', '政策', '措施', '任务', '目标', '要求', '重点', '保障',
'支持', '服务', '管理', '改革', '创新', '协调', '绿色', '开放', '共享'
])

def get_gov_report():
url = "http://www.gov.cn/zhengce/2023-03/14/content_5746918.htm"

try:
    response = requests.get(url)
    response.encoding = 'utf-8'
    html = response.text
    
    content = re.sub(r'<[^>]+>', '', html)
    content = re.sub(r'\s+', ' ', content)
    
    # 如果获取失败,使用示例文本(实际应用中应处理错误)
    if len(content) < 1000:
        print("网络获取内容过短,使用示例文本")
        with open('gov_report_sample.txt', 'r', encoding='utf-8') as f:
            content = f.read()
    
    return content
except Exception as e:
    print(f"获取政府工作报告失败: {e}")
    # 使用本地示例文件作为后备
    with open('gov_report_sample.txt', 'r', encoding='utf-8') as f:
        return f.read()

文本预处理和分词

def process_text(text):
words = jieba.lcut(text)

filtered_words = [
    word for word in words 
    if len(word) > 1 
    and word not in custom_stopwords
    and not re.match(r'\d+', word)
    and not re.match(r'[^\u4e00-\u9fa5]', word)
]

return filtered_words

def extract_keywords(text, top_n=100):

keywords = jieba.analyse.extract_tags(
    text, 
    topK=top_n, 
    withWeight=True, 
    allowPOS=('n', 'vn', 'v', 'ns', 'nt', 'nz')
)

keyword_dict = {word: weight for word, weight in keywords}
return keyword_dict

生成词云

def generate_wordcloud(keyword_dict):
wc = WordCloud(
width=800,
height=600,
background_color='white',
font_path='simhei.ttf',
max_words=100,
scale=2
)

wordcloud = wc.generate_from_frequencies(keyword_dict)

plt.figure(figsize=(12, 8))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.title('政府工作报告词云分析', fontsize=16, pad=20)
plt.show()

wordcloud.to_file('government_report_wordcloud.png')
print("词云已保存为 government_report_wordcloud.png")

def main():

print("正在获取政府工作报告文本...")
report_text = get_gov_report()

print("正在进行文本预处理和分词...")
processed_words = process_text(report_text)

print("正在提取关键词...")

processed_text = ' '.join(processed_words)
keywords = extract_keywords(processed_text, top_n=100)

print("正在生成词云...")
generate_wordcloud(keywords)

print("\nTop 20 关键词:")
sorted_keywords = sorted(keywords.items(), key=lambda x: x[1], reverse=True)
for word, weight in sorted_keywords[:20]:
    print(f"{word}: {weight:.3f}")

if name == 'main':
jieba.initialize()

main()

圆形轨迹绘制引擎

import turtle
import math

class ArcDrawingEngine:
def init(self, width=800, height=600):
"""初始化绘制引擎"""
self.screen = turtle.Screen()
self.screen.setup(width, height)
self.screen.title("弧形绘制引擎")
self.t = turtle.Turtle()
self.t.speed(0)

def draw_from_file(self, filename):
    """从数据文件读取指令并绘制"""
    with open(filename, 'r') as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith('#'):
                continue
            
            parts = line.split(',')
            cmd = parts[0].lower()
            
            try:
                if cmd == 'arc':
                    # 格式: arc,radius,angle[,direction]
                    radius = float(parts[1])
                    angle = float(parts[2])
                    direction = parts[3].lower() if len(parts) > 3 else 'left'
                    self.draw_arc(radius, angle, direction)
                elif cmd == 'move':
                    # 格式: move,distance
                    distance = float(parts[1])
                    self.move(distance)
                elif cmd == 'turn':
                    # 格式: turn,angle[,direction]
                    angle = float(parts[1])
                    direction = parts[2].lower() if len(parts) > 2 else 'right'
                    self.turn(angle, direction)
                elif cmd == 'color':
                    # 格式: color,color_name
                    color = parts[1].strip()
                    self.set_color(color)
                elif cmd == 'width':
                    # 格式: width,width_value
                    width = float(parts[1])
                    self.set_width(width)
                elif cmd == 'circle':
                    # 格式: circle,radius[,direction]
                    radius = float(parts[1])
                    direction = parts[2].lower() if len(parts) > 2 else 'left'
                    self.draw_circle(radius, direction)
            except (IndexError, ValueError) as e:
                print(f"指令解析错误: {line} - {str(e)}")

def draw_arc(self, radius, angle, direction='left'):
    """
    绘制弧形
    :param radius: 半径
    :param angle: 角度
    :param direction: 方向(left/right)
    """
    step = 1
    steps = int(angle / step)
    step_length = 2 * math.pi * radius * step / 360
    
    if direction.lower() == 'left':
        for _ in range(steps):
            self.t.left(step)
            self.t.forward(step_length)
    else:
        for _ in range(steps):
            self.t.right(step)
            self.t.forward(step_length)

def draw_circle(self, radius, direction='left'):
    """绘制完整圆形"""
    self.draw_arc(radius, 360, direction)

def move(self, distance):
    """移动画笔,不绘制"""
    self.t.penup()
    self.t.forward(distance)
    self.t.pendown()

def turn(self, angle, direction='right'):
    """转向"""
    if direction.lower() == 'right':
        self.t.right(angle)
    else:
        self.t.left(angle)

def set_color(self, color):
    """设置画笔颜色"""
    self.t.color(color)

def set_width(self, width):
    """设置画笔宽度"""
    self.t.width(width)

def keep_open(self):
    """保持窗口打开"""
    turtle.done()

sample_data = """# 弧形绘制示例数据文件

绘制一个由弧形组成的圆形轨迹

设置红色画笔,宽度3

color,red
width,3

绘制一个完整的圆形(半径100)

circle,100

移动到新位置

move,150
turn,90

绘制半圆

color,blue
arc,50,180

绘制四分之一圆

move,100
color,green
arc,75,90,right
"""

with open('arc_patterns.dat', 'w') as f:
f.write(sample_data)

if name == "main":
engine = ArcDrawingEngine()
engine.draw_from_file('arc_patterns.dat')
engine.keep_open()

Logo词云绘制

from wordcloud import WordCloud, ImageColorGenerator
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import jieba

poem = """
黄鹤楼送孟浩然之广陵
李白
故人西辞黄鹤楼,烟花三月下扬州。
孤帆远影碧空尽,唯见长江天际流。
"""

text = " ".join(jieba.cut(poem))

logo_path = "gpnulogo.png"

try:
logo_mask = np.array(Image.open(logo_path))
except:
print("未找到logo图片,将使用圆形作为替代形状")
x, y = np.ogrid[:300, :300]
logo_mask = (x - 150) ** 2 + (y - 150) ** 2 > 130 ** 2
logo_mask = 255 * logo_mask.astype(int)

wc = WordCloud(
font_path="simhei.ttf",
background_color="white",
max_words=200,
mask=logo_mask,
max_font_size=100,
random_state=42,
contour_width=1,
contour_color='steelblue'
)

wc.generate(text)

try:
image_colors = ImageColorGenerator(logo_mask)
wc.recolor(color_func=image_colors)
except:
pass

plt.figure(figsize=(10, 8))
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.title("广东技术师范大学Logo词云 - 李白《黄鹤楼》", pad=20)
plt.show()

wc.to_file("gpnulogo_wordcloud.png")
print("词云已保存为 gpnulogo_wordcloud.png")

英语词典

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(' ', 1)
if len(parts) == 2:
english, chinese = parts
dictionary[english] = chinese
return dictionary

def save_dictionary(file_path, dictionary):
"""将词典保存到文件"""
with open(file_path, 'w', encoding='utf-8') as f:
for english, chinese in dictionary.items():
f.write(f"{english} {chinese}\n")

def add_word(dictionary):
"""添加单词功能"""
english = input("请输入英文单词: ").strip()
if english in dictionary:
print("该单词已添加到字典库")
else:
chinese = input("请输入中文释义: ").strip()
dictionary[english] = chinese
print("单词添加成功!")

def query_word(dictionary):
"""查询单词功能"""
english = input("请输入要查询的英文单词: ").strip()
chinese = dictionary.get(english)
if chinese:
print(f"中文释义: {chinese}")
else:
print("字典库中未找到这个单词")

def main():
file_path = "dictionary.txt"

dictionary = load_dictionary(file_path)

while True:
    print("\n英语学习词典")
    print("1. 添加单词")
    print("2. 查询单词")
    print("3. 退出")
    
    choice = input("请选择功能(1/2/3): ").strip()
    
    if choice == '1':
        add_word(dictionary)
    elif choice == '2':
        query_word(dictionary)
    elif choice == '3':
        save_dictionary(file_path, dictionary)
        print("词典已保存,再见!")
        break
    else:
        print("输入有误,请重新输入!")

if name == "main":
main()

英语词典pro max

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(' ', 1)
if len(parts) == 2:
english, chinese = parts
dictionary[english] = chinese
return dictionary

def save_dictionary(file_path, dictionary):
"""将词典保存到文件,保持多重释义格式"""
with open(file_path, 'w', encoding='utf-8') as f:
for english, chinese in dictionary.items():
f.write(f"{english} {chinese}\n")

def add_word(dictionary):
"""添加单词功能,支持多重释义"""
english = input("请输入英文单词: ").strip().lower()
chinese_existing = dictionary.get(english, "")

if chinese_existing:
    print(f"当前释义: {chinese_existing}")
    choice = input("该单词已存在,要添加新释义吗?(y/n): ").strip().lower()
    if choice == 'y':
        new_chinese = input("请输入新增的中文释义: ").strip()
        updated_chinese = f"{chinese_existing}, {new_chinese}"
        dictionary[english] = updated_chinese
        print("新释义添加成功!")
    else:
        print("未添加新释义")
else:
    chinese = input("请输入中文释义(可输入多个,用逗号隔开): ").strip()
    dictionary[english] = chinese
    print("单词添加成功!")

def query_word(dictionary):
"""查询单词功能,显示多重释义"""
english = input("请输入要查询的英文单词: ").strip().lower()
chinese = dictionary.get(english)
if chinese:
print("\n查询结果:")
print(f"英文单词: {english}")
print("中文释义:")
meanings = [m.strip() for m in chinese.split(',')]
for i, meaning in enumerate(meanings, 1):
print(f"{i}. {meaning}")
else:
print("字典库中未找到这个单词")

def main():
file_path = "dictionary.txt"

dictionary = load_dictionary(file_path)

while True:
    print("\n英语学习词典 (支持多重释义)")
    print("1. 添加单词")
    print("2. 查询单词")
    print("3. 退出")
    
    choice = input("请选择功能(1/2/3): ").strip()
    
    if choice == '1':
        add_word(dictionary)
    elif choice == '2':
        query_word(dictionary)
    elif choice == '3':
        save_dictionary(file_path, dictionary)
        print("词典已保存,再见!")
        break
    else:
        print("输入有误,请重新输入!")

if name == "main":
main()

posted @ 2025-05-18 11:08  HeDesongfuqin  阅读(66)  评论(0)    收藏  举报