2013-05-20 46 views
22

Creating a subset of words from a corpus in R,回答者可以很容易地将一个term-document matrix转换成一个文字云很容易。如何从Python中的语料库创建词云?

是否有类似于python库的函数,它可以将原始文本文件或NLTK语料库或​​Mmcorpus转换为词云?

结果看起来有点像这样: enter image description here

+1

经过一番疯狂的重新实现之后,这里是无耻的插件,但是这里有一个不太“sklearn”的解决方案,它使用了Andreas Mueller的代码。 https://github.com/alvations/translation-cloud – alvas

回答

10

如果您需要这些词云为了在网站或网络应用程序中显示它们,您可以将数据转换为json或csv格式并将其加载到JavaScript可视化库(如d3)中。 Word Clouds on d3

如果不是,Marcin的答案是做你描述的一个好方法。

3

的amueller在动作

在命令行/终端的代码示例:

sudo pip install wordcloud 

然后运行Python脚本:

# Simple WordCloud 
from os import path 
from scipy.misc import imread 
import matplotlib.pyplot as plt 
import random 

from wordcloud import WordCloud, STOPWORDS 

text = 'all your base are belong to us all of your base base base' 
wordcloud = WordCloud(font_path='/Library/Fonts/Verdana.ttf', 
         relative_scaling = 1.0, 
         stopwords = {'to', 'of'} # set or space-separated string 
        ).generate(text) 
plt.imshow(wordcloud) 
plt.axis("off") 
plt.show() 

enter image description here

+0

其实这是一个很具欺骗性的文字云。鉴于它是基于像素和单词的长度进行归一化的,尽管计数是相同的,这就是美国大于基数的原因。 – alvas

+0

查看文档。可以改变停用词和relative_scaling(缩放词时的频率与等级)图。默认情况下,relative_scaling是0(Rank),我相信你正在寻找relative_scaling = 1.0(频率)。 – MyopicVisage

+0

你可以把它放入答案吗?还用1.0生成不同的词云?谢谢!这将有助于未来的读者=) – alvas

1
from wordcloud import WordCloud, STOPWORDS 
stopwords = set(STOPWORDS) 

def show_wordcloud(data, title = None): 
    wordcloud = WordCloud(
     background_color='white', 
     stopwords=stopwords, 
     max_words=200, 
     max_font_size=40, 
     scale=3, 
     random_state=1 # chosen at random by flipping a coin; it was heads 
    ).generate(str(data)) 

    fig = plt.figure(1, figsize=(12, 12)) 
    plt.axis('off') 
    if title: 
     fig.suptitle(title, fontsize=20) 
     fig.subplots_adjust(top=2.3) 

    plt.imshow(wordcloud) 
    plt.show() 

show_wordcloud(Samsung_Reviews_Negative['Reviews']) 
show_wordcloud(Samsung_Reviews_positive['Reviews']) 

enter image description here

相关问题