编写一个python程序,统计三国演义里的人物
时间: 2024-02-15 16:04:10 浏览: 26
好的,以下是一个简单的Python程序,用于统计《三国演义》中出现的人物及其出现次数:
```python
import re
# 读取三国演义文本
with open('sgyy.txt', 'r', encoding='utf-8') as f:
sgyy_text = f.read()
# 使用正则表达式匹配人物名称
pattern = re.compile(r'[\u4e00-\u9fa5]{2,5}(?:·[\u4e00-\u9fa5]{2,5})*')
characters = pattern.findall(sgyy_text)
# 统计人物出现次数
character_dict = {}
for character in characters:
if character in character_dict:
character_dict[character] += 1
else:
character_dict[character] = 1
# 打印结果
for character, count in character_dict.items():
print(f'{character}: {count}')
```
你可以将程序保存为一个文件,比如`sgyy_characters.py`,然后在命令行中执行`python sgyy_characters.py`,程序会读取当前目录下的`sgyy.txt`文件(请确保该文件存在,并且是UTF-8编码的文本文件),并输出每个人物的出现次数。
相关问题
用python编写程序完成《三国演义》人物出场统计。
以下是两种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))
```
编写python程序,统计,《三国演义》中前20位出场的人物的次数
好的,我可以帮你编写这个程序。不过在开始之前,需要先将《三国演义》的文本文件准备好,并保存在程序可以访问的路径下。
以下是可能的程序实现方式:
```python
import re
# 读取《三国演义》文本文件
with open('path/to/sgyy.txt', 'r', encoding='utf-8') as f:
sgyy = f.read()
# 使用正则表达式匹配出所有人物名称
pattern = r'[\u4e00-\u9fa5]{2,5}(?:·[\u4e00-\u9fa5]{2,5})*'
matches = re.findall(pattern, sgyy)
# 统计人物出场次数
count_dict = {}
for name in matches:
count_dict[name] = count_dict.get(name, 0) + 1
# 获取前20个出场最多的人物
top20 = sorted(count_dict.items(), key=lambda x: x[1], reverse=True)[:20]
# 输出结果
for i, (name, count) in enumerate(top20):
print(f'{i+1}. {name}: {count}次')
```
需要注意的是,以上程序只是一个可能的实现方式,具体实现可能会因文本格式、文本内容等因素而有所不同,需要根据具体情况进行调整。