python使用字典制作词云
时间: 2024-01-04 08:18:35 浏览: 97
使用Python中的字典可以很方便地制作词云。下面是一个简单的示例代码,它将文本中的单词作为字典的键,出现的次数作为字典的值,然后使用wordcloud库生成词云图像。
```python
import wordcloud
# 读取文本文件
with open('text.txt', 'r') as f:
text = f.read()
# 将文本分割成单词
words = text.split()
# 统计单词出现的次数
word_counts = {}
for word in words:
if word not in word_counts:
word_counts[word] = 0
word_counts[word] += 1
# 生成词云图像
wc = wordcloud.WordCloud()
wc.generate_from_frequencies(word_counts)
wc.to_file('wordcloud.png')
```
在这个示例中,我们首先使用`open()`函数读取文本文件,然后使用`split()`方法将文本分割成单词。接着,我们使用一个字典`word_counts`来统计每个单词出现的次数。最后,我们使用`WordCloud()`函数创建一个词云对象,使用`generate_from_frequencies()`方法将字典中的键值对转换为词频,最后使用`to_file()`方法将词云图像保存为文件。
相关问题
python用词频制作词云图
制作Python词云图的重要一步是将文本中的单词转换为单词频率,这个可以使用Python中的collections库中的Counter函数来实现。下面是一个简单的示例代码,展示如何使用词频制作词云图:
```
import jieba
from collections import Counter
from wordcloud import WordCloud
# 读取文本
with open('text.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 分词
words = jieba.cut(text)
# 去除停用词
stopwords = set(['的', '是', '我', '你', '他', '她', '我们', '你们', '他们'])
filtered_words = [word for word in words if word not in stopwords]
# 统计词频
word_count = Counter(filtered_words)
# 制作词云
wc = WordCloud(font_path='msyh.ttc', width=800, height=600)
wc.generate_from_frequencies(word_count)
# 保存词云图
wc.to_file('wordcloud.png')
```
代码中,通过使用jieba库对文本进行分词,并使用collections库中的Counter函数统计每个词出现的次数。接着,使用WordCloud库生成词云图,其中的generate_from_frequencies()函数接受一个字典,字典的键表示单词,字典的值表示单词出现的次数,根据单词出现的次数设置单词的大小,最后将生成的词云图保存到本地。
python爬取制作词云
### 使用Python实现网页爬虫和词云生成
#### 导入所需库
为了完成这个任务,需要安装并导入一些必要的库。`requests` 和 `BeautifulSoup` 是用于网页抓取的主要工具;而 `jieba` 以及 `wordcloud` 或者 `pyecharts.charts.WordCloud` 则是用来处理中文分词及创建词云图表的关键组件。
```python
import requests
from bs4 import BeautifulSoup
import jieba
from collections import Counter
from wordcloud import WordCloud
import matplotlib.pyplot as plt
```
#### 获取网页内容
通过向目标网站发送HTTP请求来获取HTML页面的内容,并利用BeautifulSoup解析这些数据,提取出感兴趣的文本部分[^3]。
```python
url = "https://movie.douban.com/top250"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
comments = []
for div in soup.find_all('div', class_='item'):
comment_tag = div.find('span', attrs={'class': 'inq'})
if comment_tag is not None:
comments.append(comment_tag.string.strip())
```
#### 文本预处理与分析
对收集到的评论进行清洗、去除停用词等操作之后,可以使用结巴分词(`jieba`)来进行词语分割,统计每个单词出现频率形成字典形式的数据结构以便后续绘图使用。
```python
stopwords = set()
with open('path_to_stop_words.txt') as f:
stopwords.update(line.strip() for line in f)
cutted_comments = [' '.join(jieba.cut(comm)) for comm in comments]
filtered_words = [word for sentence in cutted_comments for word in sentence.split() if word not in stopwords]
word_counts = dict(Counter(filtered_words))
```
#### 绘制词云图像
最后一步就是调用相应的API函数绘制最终的结果可视化图形——词云图。这里提供了两种方式:一种是直接采用`wordcloud`包快速简便地生成静态图片文件;另一种则是借助于更灵活强大的`pyecharts`框架构建交互式的Web端展示效果[^2]。
##### 方法一:使用`wordcloud`生成静态图片
```python
wc = WordCloud(font_path='simhei.ttf', background_color="white", width=800, height=600).generate_from_frequencies(word_counts)
plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
plt.show()
wc.to_file('douban_top_250_word_cloud.png')
```
##### 方法二:使用`pyecharts`生成动态词云
```python
from pyecharts.charts import WordCloud
wd = WordCloud()
data_pairs = list(word_counts.items())[:100] # 取前100个高频词汇作为样本显示
wd.add("", data_pairs, word_size_range=[20, 100])
wd.render("douban_movie_reviews_wordcloud.html")
```
阅读全文
相关推荐














