python 3、编写程序,完成《水浒传》前70回中前5个高频词统计
时间: 2024-02-22 08:55:39 浏览: 157
好的,我可以帮你编写这个程序。首先,我们需要获取《水浒传》前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库。
希望这能帮到你!
相关问题
Python编程完成水浒传前70回的前5个高频词统计
好的,我可以为您完成这个任务。以下是Python代码:
```python
import jieba
from collections import Counter
# 读取水浒传前70回的文本文件
with open('shuihuzhuan.txt', 'r', encoding='utf8') as f:
text = f.read()
# 使用jieba分词并去除停用词
stopwords = [',', '。', '!', '?', '、', ':', ';', '\n', '的', '了', '是', '在', '他', '她', '你', '我', '我们']
words = [word for word in jieba.cut(text) if word not in stopwords]
# 统计前5个高频词
word_count = Counter(words)
top5 = word_count.most_common(5)
# 输出结果
for word, count in top5:
print(f'{word}: {count}')
```
请将文本文件保存为`shuihuzhuan.txt`,然后运行上述代码即可输出前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个高频词。最后打印出结果。
请注意,这个程序只能处理中文文本。如果你有其他语言的文本需要处理,需要使用相应的分词工具。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)