2017-02-27 112 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:謝謝。我更新了答案,希望它不會誤導未來的讀者。 –

相關問題