用jieba库编写程序统计《水浒传》中前10位出场最多的人物。
时间: 2024-11-29 07:38:30 浏览: 245
在Python中,我们可以使用jieba库进行分词,并结合字典数据结构来统计《水浒传》中人物的出场次数。首先需要准备一份《水浒传》文本数据,然后按照以下步骤操作:
1. **安装jieba库**:如果你还没有安装,可以使用`pip install jieba`命令进行安装。
```bash
pip install jieba
```
2. **下载并加载词典**:jieba需要大词典来进行精确的分词,你可以从其官方网站下载`dict.txt.big`文件。
3. **读取并预处理文本**:
- 读取文本文件,去除无关字符如标点符号。
- 使用jieba的`lcut`函数对文本进行分词。
4. **统计人物出场次数**:
- 创建一个空字典存储每个角色及其出现次数。
- 遍历分词结果,如果词语是一个人名,则更新对应的计数。
5. **筛选出前10位**:
- 对字典按值降序排序,获取出现次数最多的前10个人物。
下面是一个简化的示例代码,假设已经有一个名为`water浒传.txt`的文本文件:
```python
import jieba
# 步骤3和4
def process_text(file_name):
with open(file_name, 'r', encoding='utf-8') as f:
text = f.read().replace(',', '').replace('。', '') # 去除逗号和句号
words = jieba.lcut(text)
character_count = {}
for word in words:
if is_person_name(word): # 假设is_person_name()函数用于判断是否为人名
if word in character_count:
character_count[word] += 1
else:
character_count[word] = 1
# 步骤5
top_10_characters = sorted(character_count.items(), key=lambda x: x[1], reverse=True)[:10]
return top_10_characters
# 假设你需要添加一个人名识别函数
def is_person_name(name):
# 实现具体的判断逻辑,例如使用已有的人名列表或命名规则
pass
# 调用函数并打印结果
top_10 = process_text("water浒传.txt")
for i, (character, count) in enumerate(top_10):
print(f"{i+1}. {character}: {count} 出场")
阅读全文
相关推荐


















