如何用python对一篇给出的中文文章中的名词、动词和形容词做词频统计并绘制词云图。
时间: 2024-01-22 18:18:23 浏览: 80
要实现这个任务,我们需要使用到以下几个 Python 库:
- jieba:中文分词库
- wordcloud:词云图生成库
- matplotlib:数据可视化库
首先,我们需要安装以上三个库,可以使用以下命令:
```
pip install jieba wordcloud matplotlib
```
安装完成后,我们可以开始编写代码。
```python
import jieba
import matplotlib.pyplot as plt
from wordcloud import WordCloud
# 读取文章内容
with open('article.txt', 'r', encoding='utf-8') as f:
content = f.read()
# 对文章进行分词
words = jieba.cut(content)
# 定义词频统计字典
freq_dict = {}
# 遍历分词结果,统计词频
for word in words:
if len(word) < 2:
continue
if word in freq_dict:
freq_dict[word] += 1
else:
freq_dict[word] = 1
# 提取名词、动词和形容词
nouns = []
verbs = []
adjs = []
for word, freq in freq_dict.items():
pos = jieba.lcut(word, HMM=False)[0]
if pos == 'n':
nouns.append((word, freq))
elif pos == 'v':
verbs.append((word, freq))
elif pos == 'a':
adjs.append((word, freq))
# 绘制名词词云图
noun_wc = WordCloud(font_path='msyh.ttc', width=800, height=600, background_color='white')
noun_wc.generate_from_frequencies(dict(nouns))
plt.imshow(noun_wc, interpolation='bilinear')
plt.axis('off')
plt.show()
# 绘制动词词云图
verb_wc = WordCloud(font_path='msyh.ttc', width=800, height=600, background_color='white')
verb_wc.generate_from_frequencies(dict(verbs))
plt.imshow(verb_wc, interpolation='bilinear')
plt.axis('off')
plt.show()
# 绘制形容词词云图
adj_wc = WordCloud(font_path='msyh.ttc', width=800, height=600, background_color='white')
adj_wc.generate_from_frequencies(dict(adjs))
plt.imshow(adj_wc, interpolation='bilinear')
plt.axis('off')
plt.show()
```
以上代码中,我们首先使用 `jieba` 库将文章进行分词,然后统计分词结果中名词、动词和形容词的词频,并分别绘制词云图。
需要注意的是,我们在分词时使用了 `jieba.lcut(word, HMM=False)[0]` 来提取词性,其中 `HMM=False` 表示关闭隐马尔可夫模型,这样可以提高分词的准确率。此外,我们还过滤了单个字和长度小于 2 的词,这些词往往没有实际意义,不应计入词频统计中。
最后,我们使用 `plt.imshow()` 和 `plt.show()` 函数来显示词云图。在显示词云图时,需要设置 `interpolation='bilinear'` 参数来改善图像质量。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)