统计《三国演义》中每个人物的出场次数,输出前10名。
时间: 2024-02-23 08:58:12 浏览: 35
好的,可以使用Python的文本处理和数据结构操作来完成这个任务。可以按照以下步骤操作:
1. 打开《三国演义》的文本文件,读取其中的内容。
2. 使用正则表达式或字符串操作,提取每个人物出现的次数,并存储到一个字典中。
3. 对字典按照出现次数进行排序,取出前10名。
4. 输出结果。
下面是代码实现:
```python
import re
# 打开《三国演义》的文本文件,读取其中的内容
with open('sanguo.txt', 'r', encoding='utf-8') as f:
content = f.read()
# 使用正则表达式或字符串操作,提取每个人物出现的次数,并存储到一个字典中
pattern = r'[\u4e00-\u9fa5]{2,5}(?:·[\u4e00-\u9fa5]{2,5})*'
results = re.findall(pattern, content)
counts = {}
for result in results:
if result in counts:
counts[result] += 1
else:
counts[result] = 1
# 对字典按照出现次数进行排序,取出前10名
top10 = sorted(counts.items(), key=lambda x: x[1], reverse=True)[:10]
# 输出结果
print('三国演义中出现次数前10的人物为:')
for i, (name, count) in enumerate(top10):
print('第{}名:{},出现次数:{}'.format(i+1, name, count))
```
这样,就完成了对《三国演义》中每个人物的出场次数统计,并输出了前10名出场次数最多的人物。