用python分析四大名著之三国演义

用Python统计《三国演义》人物出场次数

点击上方“程序人生”,选择“置顶公众号”

第一时间关注程序猿(媛)身边的故事



项目起因及意义


起初在浏览知乎时看见一篇文章觉得很有意思(用 Python 分析《红楼梦》),此文章较长,题主采用了一系列方法分析红楼梦前八十回和后四十回是否为同一个人所写,虽然题主贴上了部分实现的截图,我就想试着来实现一遍,但由于目前能力有限,一些机器学习算法不够了解,加上 python 又是刚刚学,所以我打算先结合《Python 语言程序设计基础》这本书上的例子——《三国演义》人物出场统计来作为此系列博客第一篇,后续等能力足矣会陆陆续续补上。


前期准备


三国里人物众多,我们需要对人物出场次数统计,中文文章需要分词才能进行词频统计,这里我们用到第三方库 jieba,这里我就不提供下载方法了,然后我们需要《三国演义》的电子书网上都有,很容易下载。


项目进行


将文本数据导入 pycharm


import jieba
txt = open("三国演义.txt""r", encoding="gb18030").read()



这里的编码格式一开始我是按照书上‘utf-8’格式读取,发现会乱码,后来在pycharm里面用‘gbk’格式能读出文本内容,但是个别字符识别不出来,就去百度到“gb18030”比gbk范围更广,这里我成功读入。如果你此时还是读入不了可以写成下面形式


txt = open("三国演义.txt""r", encoding="gb18030",errors="ignore").read()


完整代码实现


import jieba
excludes = {"将军""却说""荆州""二人""不可""不能""如此""商议""如何""主公""军士""左右""军马""引兵""次日""大喜""天下""东吴""于是""今日""不敢""魏兵","人马""陛下""一人"}
txt = open("三国演义.txt""r", encoding="gbk").read()
words = jieba.lcut(txt)
counts = {}
for word in words:
   if len(word) == 1:
       continue
   elif word == "诸葛亮" or word == "孔明曰":
       rword = "孔明"
   elif word == "关公" or word == "云长":
       rword = "关羽"
   elif word == "玄德" or word == "玄德曰":
       rword = "刘备"
   elif word == "孟德" or word == "丞相":
       rword = "曹操"
   else:
       rword = word
   counts[rword] = counts.get(rword, 0) + 1
for word in excludes:
   del(counts[word])
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True)
for i in range(10):
   word, count=items[i]
   print (word, count)


excludes里面定义了一些出现次数较多但不是人名的词,这里主要语句就是 counts[rword] = counts.get(rword, 0) + 1 这一句字典类型的counts,如果word在counts中,返回word对应的值,否则返回0。后面用sort()函数和匿名函数lambda()进行排序,这里字典没有顺序,需要先转化为列表类型。输出结果如下: 



导出数据文件


fo = open("三国人物出场次数.txt""a")
for i in range(10):
   word, count=items[i]
   word = str(word)
   count = str(count)
   fo.write(word)
   fo.write(' ')
   fo.write(count)
   fo.write('\n')
   print (word, count)
print(items)
fo.close()


这里我们将数据导入到 三国人物出场次数.txt 这个文件里面。 


将数据画出气泡图

 


总结


由此可知“曹操“,“ 孔明””刘备”是出场最多的人,这些只是简单的数据分析,作为此系列博客的开头篇,随着学习希望自己能实现完整用python分析四大名著。


点击图片get往期内容

### 使用Python获取或处理中国四大名著文本数据的方法 #### 1. 获取四大名著文本数据 可以通过网络爬虫技术从公开的网站下载四大名著的文本数据。例如,使用 `requests` 和 `BeautifulSoup` 库可以从古诗文网等网站抓取《三国演义》、《红楼梦》、《水浒传》和《西游记》的文本内容[^1]。 ```python import requests from bs4 import BeautifulSoup def fetch_text_from_url(url): response = requests.get(url) if response.status_code == 200: soup = BeautifulSoup(response.text, 'html.parser') text = soup.get_text() return text else: return None # 示例:从某个网站抓取《三国演义》的文本 url = "https://www.gushiwen.cn/shiwenv_三国演义.aspx" text = fetch_text_from_url(url) if text: with open("三国演义.txt", "w", encoding="utf-8") as f: f.write(text) ``` #### 2. 处理四大名著文本数据 一旦获取到文本数据,可以使用 `jieba` 分词库对文本进行分词,并统计词频或生成词云图[^2]。 ```python import jieba from wordcloud import WordCloud import matplotlib.pyplot as plt def process_text(file_path): with open(file_path, "r", encoding="utf-8") as f: text = f.read() words = jieba.lcut(text) word_freq = {} for word in words: if len(word) > 1: # 过滤掉单个字符 word_freq[word] = word_freq.get(word, 0) + 1 return word_freq def generate_word_cloud(word_freq, output_file): wc = WordCloud(font_path="msyh.ttc", width=800, height=400, background_color="white") wc.generate_from_frequencies(word_freq) wc.to_file(output_file) # 示例:处理《三国演义》文本并生成词云 file_path = "三国演义.txt" word_freq = process_text(file_path) generate_word_cloud(word_freq, "三国演义词云.png") ``` #### 3. 可视化分析 除了生成词云,还可以绘制词频分布的饼状图或柱状图[^5]。 ```python def plot_word_frequency(word_freq, top_n=10): sorted_words = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)[:top_n] labels, sizes = zip(*sorted_words) plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90) plt.title("Top {} Words Frequency".format(top_n)) plt.show() # 示例:绘制《三国演义》的词频分布饼状图 plot_word_frequency(word_freq, top_n=10) ``` #### 4. 深度学习应用 对于更高级的自然语言处理任务,如情感分析或主题建模,可以结合深度学习框架 PyTorch 或 TensorFlow 来实现[^4]。 ```python import torch from transformers import BertTokenizer, BertForSequenceClassification def load_model_and_tokenizer(): tokenizer = BertTokenizer.from_pretrained('bert-base-chinese') model = BertForSequenceClassification.from_pretrained('bert-base-chinese') return tokenizer, model def classify_text(tokenizer, model, text): inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True) outputs = model(**inputs) logits = outputs.logits predicted_class = torch.argmax(logits, dim=-1).item() return predicted_class # 示例:加载模型并对一段文本进行分类 tokenizer, model = load_model_and_tokenizer() text = "刘备初见诸葛亮" predicted_class = classify_text(tokenizer, model, text) print(f"Predicted Class: {predicted_class}") ``` ---
评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值