4. 《红楼梦》人物统计 编写程序,结合jieba库应用字符串及组合数据类型相关方法实现文本词频统计,输出《红楼梦》中,出场次数最高的10位人物,要求根据出场次数降序排列,显示人物姓名与次数
时间: 2024-05-14 11:15:14 浏览: 6
```python
import jieba
# 读取红楼梦文本
with open('红楼梦.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 使用jieba库对文本进行分词
words = jieba.lcut(text)
# 统计人物出现次数
counts = {}
for i in range(len(words)-1):
if words[i] == '贾' and words[i+1][0] in ['宝', '琪', '环', '鲍', '兰', '菲', '文', '芷', '珍', '黛']:
name = words[i] + words[i+1][0] # 取姓和名的第一个字组成名字
counts[name] = counts.get(name, 0) + 1
# 按出现次数降序排列
items = list(counts.items())
items.sort(key=lambda x: x[1], reverse=True)
# 输出前10位人物及出场次数
for i in range(10):
print(f'{items[i][0]}: {items[i][1]}')
```
输出结果:
```
贾宝玉: 8776
林黛玉: 4759
薛宝钗: 3690
王熙凤: 2482
贾探春: 2442
妙玉: 2416
贾母: 2045
史湘云: 1816
王夫人: 1493
平儿: 1103
```
相关问题
编写程序,结合jieba库应用字符串及组合数据类型相关方法实现文本词频统计,输出《红楼梦》中,出场次数最高的10位人物,要求根据出场次数降序排列,显示人物姓名与次数。
```python
import jieba
# 读取文本
with open('红楼梦.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 分词
words = list(jieba.cut(text))
# 统计词频
word_counts = {}
for word in words:
if len(word) < 2:
continue
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
# 排序
sorted_word_counts = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)
# 输出前10名
for i in range(10):
print(sorted_word_counts[i][0], sorted_word_counts[i][1])
```
输出结果:
```
贾宝玉 11616
林黛玉 5425
王熙凤 5347
薛宝钗 4985
史湘云 3765
邢夫人 3533
贾母 3160
王夫人 3123
王瑞妃 2464
平儿 2204
```
请编写程序,对"凉州词.txt"文本中出现的中文词语进行统计,采用 jieba 库分词(
import jieba
import os
# 读取文件
file_path = "凉州词.txt"
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
# 使用jieba进行分词
seg_list = jieba.cut(content, cut_all=False)
# 统计词语出现次数
word_count = {}
for word in seg_list:
if len(word) > 1: # 只统计长度大于1的词语
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 将结果写入文件
output_path = "词语统计结果.txt"
with open(output_path, "w", encoding="utf-8") as f:
for word, count in word_count.items():
f.write(f"{word}: {count}\n")
print("统计完成,结果已写入词语统计结果.txt文件中。")