python 3、编写程序,完成《水浒传》前70回中前5个高频词统计
时间: 2024-02-22 12:55:39 浏览: 16
好的,我可以帮你编写这个程序。首先,我们需要获取《水浒传》前70回的文本,然后对文本进行分词,统计每个词的出现次数,最后选出前5个高频词。
我们可以使用Python中的jieba库进行分词,使用collections库中的Counter进行统计。
以下是完整的代码:
```python
import jieba
from collections import Counter
# 读取文本内容
with open('shuihuzhuan.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 对文本进行分词
words = jieba.cut(text)
# 统计每个词的出现次数
word_counts = Counter(words)
# 选出前5个高频词
top5 = word_counts.most_common(5)
# 输出结果
print('前5个高频词:')
for word, count in top5:
print(f'{word}: {count}')
```
请确保shuihuzhuan.txt文件在程序所在的文件夹中,或者更改文件路径。同时,需要安装jieba库。
希望这能帮到你!
相关问题
编写程序,完成水浒传前70回中前5个高频词统计
以下是一种Python实现方式:
```python
# 读取文本
with open('shuihuzhuan.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 去除标点符号
import string
text = text.translate(str.maketrans('', '', string.punctuation))
# 分词
import jieba
words = jieba.lcut(text)
# 统计词频
from collections import Counter
word_counts = Counter(words)
# 排序并输出前5个高频词
top_words = word_counts.most_common(5)
for word, count in top_words:
print(word, count)
```
需要注意的是,这里使用了jieba分词库和collections.Counter类,如果没有安装的话需要先进行安装。对于文本的处理,我们去除了所有标点符号,这样可以更准确地统计高频词。最后,我们使用most_common方法来获取词频最高的5个词,并输出它们的出现次数。
编写程序,完成《水浒传》前70回中前5个高频词统计。
好的,这里提供一个Python的实现方法:
```python
import jieba
from collections import Counter
# 读取《水浒传》前70回的文本文件
with open('shuihuzhuan.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 使用jieba分词,并过滤掉单个字的词语
words = [word for word in jieba.cut(text) if len(word) > 1]
# 统计词频并取前5个高频词
top5 = Counter(words).most_common(5)
# 打印结果
for word, count in top5:
print(word, count)
```
在运行之前,需要先安装jieba库。
这段代码将读取名为“shuihuzhuan.txt”的文本文件,使用jieba分词并过滤掉单个字的词语,然后统计词频并取前5个高频词。最后打印出结果。
请注意,这个程序只能处理中文文本。如果你有其他语言的文本需要处理,需要使用相应的分词工具。