用Python生成字频图的方法?

2024-04-20 13:10:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件,其中包含一个单词和它出现的频率。我想生成一种图,我要找一种类似“气泡”的图形。这个想法是,这些气泡的大小与相对频率相对应,并在这些气泡上标注相应的单词。有人知道这是否可以用标准matplotlib或类似的工具来实现吗?在


Tags: 文件工具图形标准matplotlib单词气泡频率
2条回答

there之外有很多库。在

下面是一个来自WordCloud的示例

#!/usr/bin/env python
"""
Minimal Example
===============
Generating a square wordcloud from the US constitution using default arguments.
"""

import os

from os import path
from wordcloud import WordCloud

# using word frequency list:
#word_freq = open("/tmp/word_freq.txt").read()
# say it looks like this:
word_freq = {'apple': 4, 'banana': 1, 'melon': 2, 'strawberry': 3, 'grape': 8}
text = " ".join([(k + " ")*v for k,v in word_freq.items()])

# Generate a word cloud image
wordcloud = WordCloud().generate(text)


# Display the generated image:
# the matplotlib way:
import matplotlib.pyplot as plt
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")

# lower max_font_size
wordcloud = WordCloud(max_font_size=40).generate(text)
plt.figure()
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.show()

# The pil way (if you don't have matplotlib)
# image = wordcloud.to_image()
# image.show()

来自不同文本的WordCloud: wordcloud

让我们来看看频率

下面的代码应该行得通

导入操作系统

from os import path
from wordcloud import WordCloud
import matplotlib.pyplot as plt

data = {
    'Bla': 10,
    'Bl': 2,
    'cold' : 9,
    'random': 6
}
wordcloud = WordCloud(max_font_size=40).generate(" ".join([(k + ' ') * v for k,v in data.items()]))
plt.figure()
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.show()

相关问题 更多 >