【问题标题】:generating word cloud for items in a list in python为python列表中的项目生成词云
【发布时间】:2018-01-17 05:28:20
【问题描述】:
 my_list=["one", "one two", "three"]

我正在为这个列表生成一个词云

 wordcloud = WordCloud(width = 1000, height = 500).generate(" ".join(my_list))

当我将所有项目转换为字符串时,它正在为

生成词云
   "one","two","three"

 But I want to generate word cloud for the values, "one","one two","three"

帮我为列表中的项目生成词云

【问题讨论】:

    标签: python string list word word-cloud


    【解决方案1】:

    一种做法,

    import matplotlib.pyplot as plt
    from wordcloud import WordCloud
    
    #convert list to string and generate
    unique_string=(" ").join(my_list)
    wordcloud = WordCloud(width = 1000, height = 500).generate(unique_string)
    plt.figure(figsize=(15,8))
    plt.imshow(wordcloud)
    plt.axis("off")
    plt.savefig("your_file_name"+".png", bbox_inches='tight')
    plt.show()
    plt.close()
    

    另一种方法是创建计数器字典,

    #convert it to dictionary with values and its occurences
    from collections import Counter
    word_could_dict=Counter(my_list)
    wordcloud = WordCloud(width = 1000, height = 500).generate_from_frequencies(word_could_dict)
    
    plt.figure(figsize=(15,8))
    plt.imshow(wordcloud)
    plt.axis("off")
    #plt.show()
    plt.savefig('yourfile.png', bbox_inches='tight')
    plt.close()
    

    【讨论】:

      【解决方案2】:

      WordCloud 将正则表达式作为参数。使用它,我们可以将拆分字符设为+ 而不是空格。

      regexp=r"\w[\w' ]+"
      

      然后需要在+ 上加入单词列表,并且每个单词现在都用于拆分单词。产生如下代码:

      wordcloud = WordCloud(width=1000, height=500, regexp=r"\w[\w' ]+").generate("+".join(my_list))
      

      【讨论】:

      • 我收到“KeyError: '”
      猜你喜欢
      • 1970-01-01
      • 2020-11-27
      • 1970-01-01
      • 2021-09-17
      • 1970-01-01
      • 2011-07-26
      • 1970-01-01
      • 2019-06-02
      • 1970-01-01
      相关资源
      最近更新 更多