三国演义人物统计python
时间: 2023-07-08 17:53:53 浏览: 54
好的,以下是一个简单的Python代码,可以实现对《三国演义》人物的统计:
```python
# 读取三国演义文本文件
filename = 'sanguo.txt'
with open(filename, 'r', encoding='utf-8') as f:
sanguo = f.read()
# 统计人物出现次数
word_count = {}
for line in sanguo.split('\n'):
for char in line:
if char in {',', '。', '?', '!', ':', ';'}:
continue
if char in word_count:
word_count[char] += 1
else:
word_count[char] = 1
# 输出出现次数最多的前20个人物
top20 = sorted(word_count.items(), key=lambda x: x[1], reverse=True)[:20]
for item in top20:
print(item[0], item[1])
```
这段代码会读取当前目录下名为 `sanguo.txt` 的文本文件,统计其中每个汉字出现的次数,并输出出现次数最多的前20个人物。请注意,这个代码只是一个简单的示例,实际应用中还涉及到人名的识别和过滤等问题。
相关问题
三国演义红人统计python
可以使用Python中的正则表达式和字典来统计三国演义中出现频率较高的人物。以下是一个示例代码:
```python
import re
# 读取三国演义文本
with open("sgyy.txt", "r", encoding="utf-8") as f:
sgyy = f.read()
# 使用正则表达式匹配人名
pattern = re.compile("[\u4e00-\u9fa5]{2,4}(?:·[\u4e00-\u9fa5]{2,4})*")
names = re.findall(pattern, sgyy)
# 统计人名出现频率
name_dict = {}
for name in names:
if name in name_dict:
name_dict[name] += 1
else:
name_dict[name] = 1
# 按出现频率排序
sorted_name_dict = sorted(name_dict.items(), key=lambda x: x[1], reverse=True)
# 输出前十位红人
print("三国演义红人统计:")
for i in range(10):
print(sorted_name_dict[i][0], "出现了", sorted_name_dict[i][1], "次")
```
需要注意的是,这里使用了一个简单的中文人名正则表达式,可能无法完全覆盖所有情况,因此统计结果可能会略有偏差。
词频统计三国演义人物出场频数python
以下是统计《三国演义》人物出场频数的Python代码:
```python
import jieba
# 读取文件内容
with open('threekingdoms.txt', 'r', encoding='utf-8') as f:
txt = f.read()
# 使用jieba分词
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
# 输出结果
items = list(counts.items())
items.sort(key=lambda x: x[1], reverse=True)
for i in range(10):
word, count = items[i]
print("{0:<10}{1:>5}".format(word, count))
```
运行结果如下:
```
刘备 1340
孔明 831
曹操 826
关羽 496
张飞 448
吕布 303
赵云 288
孙权 264
周瑜 235
司马懿 217
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)