用python编写程序完成《三国演义》人物出场统计。
时间: 2023-12-31 12:06:49 浏览: 120
用python写的三国小游戏.7z
以下是两种Python编写程序完成《三国演义》人物出场统计的方法:
1. 使用jieba库进行分词和统计
```python
import jieba
# 读取文件
with open('sgyy.txt', 'r', encoding='utf-8') as f:
sgyy = f.read()
# 分词
words = jieba.lcut(sgyy)
# 统计词频
counts = {}
for word in words:
if len(word) == 1: # 排除单个字符的分词结果
continue
else:
counts[word] = counts.get(word, 0) + 1
# 输出出现次数最多的前10个人物
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))
```
2. 使用numpy库进行统计
```python
import numpy as np
# 读取文件
with open('sgyy.txt', 'r', encoding='utf-8') as f:
sgyy = f.read()
# 将文本转换为数组
text_arr = np.array(list(sgyy))
# 统计出现次数
unique, counts = np.unique(text_arr, return_counts=True)
# 将结果合并为字典
result_dict = dict(zip(unique, counts))
# 输出出现次数最多的前10个人物
items = list(result_dict.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))
```
阅读全文