2017-02-27 56 views
1

我正尝试使用python中的单词词典构建wordcloud。 这里是我的脚本Python词云 - IndexError:字符串索引超出范围

from wordcloud import WordCloud 
words = {'Python':15, 'Pandas':13, 'R':16, 'Analyis':10, 'Scikit learn':19, 'Matplotlib':10} 
wc = WordCloud() 
wcloud = wc.generate_from_frequencies(words) 

import matplotlib.pyplot as plt 
plt.imshow(wcloud) 
plt.axis("off") 
plt.figure() 
plt.imshow(wcloud) 
plt.axis("off") 
plt.show() 

我收到错误,如

wcloud = wc.generate_from_frequencies(words) 
    File "...\Anaconda3\lib\site-packages\wordcloud\wordcloud.py", line 263, in generate_from_frequencies 
    frequencies = sorted(frequencies, key=item1, reverse=True) 

IndexError: string index out of range 

有人可以帮我如何解决这个问题。 我能够为文本文件生成wordcloud。但我想通过在Python字典(例如,在上面的脚本中所示)

我在Windows 7上运行,蟒蛇的Python 3.5,自定义单词频率使用Idlex和Spyder的IDE

回答

2

wordcloud docs

static generate_from_frequencies(frequencies)

Create a word_cloud from words and frequencies.

Parameters: frequencies : array of tuples

frequencies应该是一个元组列表,并且你正在传递一个字典。

变化

wcloud = wc.generate_from_frequencies(words) 

wcloud = wc.generate_from_frequencies(list(words.items())) 

注:这个答案适用于1.2.1版本wordcloud。 Github上的当前主分支中的On 22 October 2016 the code was changed。这个尚未发布的版本(2.0?)将frequencies的数据类型从tuple更改为dict。 (该OP的代码会在新版本中正常运行。)

这里是更新的文档字符串:

def generate_from_frequencies(self, frequencies, max_font_size=None): 
    """Create a word_cloud from words and frequencies. 

    Parameters 
    ---------- 
    frequencies : dict from string to float 
     A contains words and associated frequency. 

    max_font_size : int 
     Use this font-size instead of self.max_font_size 

    Returns 
    ------- 
    self 

    """ 
+0

正如一个供参考,这在当前的主分支被改变GitHub上。 –

+0

@MadPhysicist:谢谢。我更新了答案,希望它不会误导未来的读者。 –

相关问题