代码之家  ›  专栏  ›  技术社区  ›  Pyd

在python中为列表中的项目生成词云

  •  15
  • Pyd  · 技术社区  · 7 年前
     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"
    

    2 回复  |  直到 7 年前
        1
  •  16
  •   Pyd    4 年前

    一种方法,

    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
  •  1
  •   ikkuh    7 年前

    这个 WordCloud 将正则表达式作为参数。使用这个,我们可以使分割字符 +

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

    然后需要将单词列表连接到 +

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