引言《三国演义》作为中国古典四大名著之一,以其丰富的人物形象和跌宕起伏的故事情节深受读者喜爱。本案例将带您通过Python编程入门,探索《三国演义》的奥秘,体验编程的乐趣。案例目标读取《三国演义》文本...
《三国演义》作为中国古典四大名著之一,以其丰富的人物形象和跌宕起伏的故事情节深受读者喜爱。本案例将带您通过Python编程入门,探索《三国演义》的奥秘,体验编程的乐趣。
# 读取本地《三国演义》文本文件
with open('三国演义.txt', 'r', encoding='utf-8') as file: text = file.read()import re
# 去除标点符号和特殊字符
text = re.sub(r'[ws]', '', text)
text = re.sub(r'n', '', text)import jieba
from collections import Counter
# 使用jieba进行分词
words = jieba.lcut(text)
# 统计词频
word_counts = Counter(words)
# 输出出现频率最高的10个词
print(word_counts.most_common(10))# 定义人物名称集合
characters = {'曹操', '刘备', '孙权', '诸葛亮', '司马懿', '赵云', '关羽', '张飞', '周瑜', '黄忠'}
# 统计人物出场次数
character_counts = {}
for word in words: if word in characters: character_counts[word] = character_counts.get(word, 0) + 1
# 输出人物出场次数
for character, count in character_counts.items(): print(f"{character}: {count}")import matplotlib.pyplot as plt
# 绘制词频柱状图
words, counts = zip(*word_counts.most_common(10))
plt.bar(words, counts)
plt.xlabel('Words')
plt.ylabel('Frequency')
plt.title('Top 10 Words in "Three Kingdoms"')
plt.show()
# 绘制人物出场次数饼图
labels, sizes = zip(*character_counts.items())
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
plt.title('Character Appearance Frequency in "Three Kingdoms"')
plt.show()通过本案例,我们学习了如何使用Python读取文本、进行文本预处理、分词、词频统计以及可视化展示。这些技能在处理其他文本数据时同样适用。希望您能从中获得编程的乐趣,并进一步探索Python的强大功能。