python,进行词频统计并绘制词云图。
时间: 2024-04-30 20:22:02 浏览: 102
【Python实战应用案例代码】-wordcloud词云图绘制.zip
好的,你需要安装两个库:jieba和wordcloud。可以通过以下命令进行安装:
```
pip install jieba
pip install wordcloud
```
安装完成后,可以按照以下步骤进行词频统计和绘制词云图:
1. 导入需要的库:
```python
import jieba
from collections import Counter
from wordcloud import WordCloud
import matplotlib.pyplot as plt
```
2. 读取文本文件并进行分词:
```python
with open('text.txt', 'r', encoding='utf-8') as f:
text = f.read()
words = jieba.cut(text)
```
3. 进行词频统计:
```python
counter = Counter(words)
```
4. 生成词云图:
```python
wc = WordCloud(font_path='simhei.ttf', background_color='white')
wc.generate_from_frequencies(counter)
plt.imshow(wc)
plt.axis('off')
plt.show()
```
完整的代码示例:
```python
import jieba
from collections import Counter
from wordcloud import WordCloud
import matplotlib.pyplot as plt
with open('text.txt', 'r', encoding='utf-8') as f:
text = f.read()
words = jieba.cut(text)
counter = Counter(words)
wc = WordCloud(font_path='simhei.ttf', background_color='white')
wc.generate_from_frequencies(counter)
plt.imshow(wc)
plt.axis('off')
plt.show()
```
其中,'text.txt' 是要进行词频统计和绘制词云图的文本文件。需要将其放在与代码同一目录下。同时,'simhei.ttf' 是词云图使用的字体文件,需要提前下载并放在与代码同一目录下。
阅读全文