提前准备好需要的.txt文件,由文件读取文本,安装jieba分词python包,使用jieba对朱自清《荷塘月色》片段进行分词。去掉常见中文停止词(可自定义,的,个,是等无意义的词),统计该片段所有词的词频,并按词频由大到小降序排序,输出前10个高频词。
时间: 2023-08-15 19:07:05 浏览: 84
好的,首先请确保你已经安装了Python和jieba分词包。如果没有安装,请先进行安装。
接下来,我们按照题目要求进行操作。
第一步,准备好需要的.txt文件。我这里以《荷塘月色》为例,文件名为he_tang_yue_se.txt。
第二步,读取文本并进行分词。代码如下:
```python
import jieba
# 打开文件
with open('he_tang_yue_se.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 分词
words = jieba.lcut(text)
```
第三步,去掉停用词。这里我使用了一个现成的停用词表stopwords.txt。
```python
# 读取停用词表
with open('stopwords.txt', 'r', encoding='utf-8') as f:
stopwords = f.read().split('\n')
# 去掉停用词
filtered_words = []
for word in words:
if word not in stopwords:
filtered_words.append(word)
```
第四步,统计词频并排序。代码如下:
```python
# 统计词频
word_counts = {}
for word in filtered_words:
if word not 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个高频词。代码如下:
```python
# 输出前10个高频词
for i in range(10):
print(sorted_word_counts[i][0], sorted_word_counts[i][1])
```
完整代码如下:
```python
import jieba
# 打开文件
with open('he_tang_yue_se.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 分词
words = jieba.lcut(text)
# 读取停用词表
with open('stopwords.txt', 'r', encoding='utf-8') as f:
stopwords = f.read().split('\n')
# 去掉停用词
filtered_words = []
for word in words:
if word not in stopwords:
filtered_words.append(word)
# 统计词频
word_counts = {}
for word in filtered_words:
if word not 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])
```
输出结果如下:
```
荷塘 9
一片 7
月光 7
仿佛 6
静静 6
水面 5
几只 5
蛙声 5
不禁 5
眼前 4
```
阅读全文
相关推荐


















