2

When I using WordCloud function .fit_words(), I met AttributeError: 'list' object has no attribute 'items'. It also doesn't work when I using .generate_from_frequencies(). How to figure it out? All suggestion will be appreciated. code:

wordcloud = WordCloud(font_path="simhei.ttf", background_color="white", max_font_size=80)
word_frequence = {x[0]: x[1] for x in words_stat.head(1000).values}
word_frequence_list = []
for key in word_frequence:
    temp = (key, word_frequence[key])
    word_frequence_list.append(temp)
wordcloud.fit_words(word_frequence_list)
plt.imshow(wordcloud)

word_frequence_list is

[('诺兰', 89), ('电影', 48), ('战争', 43), ('一个', 43), ('配乐', 40), ('故事', 38), ('人', 36), ('拍', 31), ('时间', 30), ('叙事', 28).....

Full code

Modified

When I use WordCloud.fit_word(), it shows AttributeError: 'list' object has no attribute 'items'. It also doesn't work when I use WordCloud.generate_from_frequencies() How to fix it? Thanks :) Code: frequencies = [(u'知乎',5),(u'小段同学',4),(u'曲小花',3),(u'中文分词',2),(u'样例',1)] wordcloud = WordCloud().fit_words(frequencies) Error

Traceback (most recent call last): File "D:/VS_Project/Python/WordCloudSample/WCSample.py", line 19, in wordcloud = WordCloud().fit_words(frequencies) File "C:\Users\AlphaGoMK\AppData\Local\Programs\Python\Python36-32\lib\site-packages\wordcloud\wordcloud.py", line 331, in fit_words return self.generate_from_frequencies(frequencies) File "C:\Users\AlphaGoMK\AppData\Local\Programs\Python\Python36-32\lib\site-packages\wordcloud\wordcloud.py", line 350, in generate_from_frequencies frequencies = sorted(frequencies.items(), key=item1, reverse=True) AttributeError: 'list' object has no attribute 'items'

https://github.com/amueller/word_cloud/issues/291

issues on github

AlphaGoMK
  • 181
  • 2
  • 14
  • Please mention where exactly is the error occurring. If possible include a gist of full trace so that it will be understandable and we will be able to help you. Current, we could not understand the issue properly. Please add the full code and trace in the question. – Jaffer Wilson Sep 01 '17 at 06:42
  • The full traceback is really a requirement here; we can be of much more help much quicker with that. – Martijn Pieters Sep 01 '17 at 06:45
  • Side-note: `word_frequence_list = list(word_frequence.items())` would be a much simpler method of producing your key-value pairs list. – Martijn Pieters Sep 01 '17 at 07:05

1 Answers1

4

fit_words want's your dictionary, not a list of key/value pairs. You can pass word_frequence directly.

wordcloud.fit_words(word_frequence)
Zach Gates
  • 4,045
  • 1
  • 27
  • 51
  • Thanks :) Your suggestion works well. It helps me a lot – AlphaGoMK Sep 01 '17 at 07:35
  • @AlphaGoMK: Awesome, glad I could help, and welcome to Stack Overflow! If you find an answer helpful, you can choose to upvote it, and if you deem it the correct answer, you can "accept" it by clicking the green checkmark. – Zach Gates Sep 04 '17 at 03:00