如何从Python中的标记词生成词云?

时间:2019-05-03 18:50:04

标签: python text-mining word-cloud

我有一个代码可以导入txt文件并使用NLTK库获取标记化的单词(就像在https://www.datacamp.com/community/tutorials/text-analytics-beginners-nltk中所做的一样)。我几乎可以轻松完成几乎所有我需要的一切,但是我正在努力用现在的单词来构建单词云,即使在网上搜索了几个小时,我也没有任何线索。

到目前为止,这是我的代码:

# Carrega bibliotecas
!pip install nltk
import nltk
from nltk.tokenize import sent_tokenize
nltk.download('punkt')
from nltk.tokenize import word_tokenize

from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator

# Import file
f = open('PNAD2002.txt','r')
pnad2002 = ""
while 1:
    line = f.readline()
    if not line:break
    pnad2002 += line

f.close()

tokenized_word=word_tokenize(pnad2002)

tokenized_word_2 = [w.lower() for w in tokenized_word]

我想使用以下代码(来自https://github.com/amueller/word_cloud/blob/master/examples/simple.py):

# Read the whole text.
text = open(path.join(d, 'constitution.txt')).read()

# 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()

但是我不知道该如何使用我的标记化单词。

1 个答案:

答案 0 :(得分:2)

您需要实例化一个WordCloud对象,然后调用generate_from_text

wc = WordCloud()
img = wc.generate_from_text(' '.join(tokenized_word_2))
img.to_file('worcloud.jpeg') # example of something you can do with the img

您可以传递给WordCloud大量自定义信息,您可以在线找到诸如以下示例:https://www.datacamp.com/community/tutorials/wordcloud-python