请用Python程序统计《西游记》人物
时间: 2023-06-20 07:05:32 浏览: 59
可以使用Python中的正则表达式和字典来实现统计《西游记》人物的功能。以下是示例代码:
```python
import re
# 读取《西游记》文本文件
with open('xiyouji.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 使用正则表达式匹配出所有人物名字
pattern = re.compile('[\u4e00-\u9fa5]{2,5}(?:·[\u4e00-\u9fa5]{2,5})*')
matches = pattern.findall(text)
# 统计每个人物出现的次数
character_dict = {}
for match in matches:
if match in character_dict:
character_dict[match] += 1
else:
character_dict[match] = 1
# 按照出现次数从高到低排序并输出结果
sorted_characters = sorted(character_dict.items(), key=lambda x: x[1], reverse=True)
for character, count in sorted_characters:
print(character, count)
```
需要注意的是,在上述代码中,我们使用了正则表达式`[\u4e00-\u9fa5]{2,5}(?:·[\u4e00-\u9fa5]{2,5})*`来匹配出所有的人物名字。这个正则表达式的意思是:匹配由两到五个汉字组成的字符串,后面可以跟着一个或多个由一个中文点号和两到五个汉字组成的字符串。这样可以匹配出类似“孙悟空”、“唐三藏”、“沙和尚”这样的人物名字。