current position:Home>Python drawing word cloud

Python drawing word cloud

2022-05-15 02:53:57Torres saint

wordcloud:

  • Install the module :pip install wordcloud
  • Basic use :
    • WordCloud(font_path, background_color, width, height, max_words).generate(xxx)
      • font_path: The font of the text
      • collocations: Whether it contains the collocation of two words , The default is true, So there will be duplicate data
      • background_color: Background color
      • width: The width of the curtain
      • height: Height of curtain
      • max_words: Maximum number of words displayed
      • generate: Read text file
  • Case study :
from wordcloud import WordCloud

with open("xxx.txt", encoding="utf-8") as r:
    #  Read the text 
    txt = r.read()
    #  Set the style of word cloud 
    wordcloud = WordCloud(font_path="xxx.ttf", collocations=False, background_color="black", width=800, height=600, max_words=50).generate(txt)
    #  Generate pictures 
    img = wordcloud.to_image()
    #  Show pictures 
    img.show()
    #  Save the picture 
    wordcloud.to_file("xxx.jpg")

jieba:

  • Install the module :pip install jieba
  • The basic format :
    • jieba.analyse.extract_tags(xxx, topK, withWeight, allowPOS)
      • xxx: Text to be processed
      • topK: Returns the number of keywords , Importance goes from high to low
      • withWeight: Returns the weight of each keyword
      • allowPOS: The part of speech to be extracted ,n Is a noun 、v It's a verb , The value passed is Yuanzu
  • Case study :
import jieba.analyse
from wordcloud import WordCloud

#  Set text content 
text = ""
#  Use jieba participle , Extract key words 
seg_list = jieba.analyse.extract_tags(text, allowPOS=("n", "v"))
#  Splice keywords into strings 
txt_str = " ".join(seg_list)

#  Set the style of word cloud 
wordcloud = WordCloud(font_path="xxx.ttf", collocations=False, background_color="black", width=800, height=600, max_words=50).generate(txt_str)
#  Generate pictures 
img = wordcloud.to_image()
#  Show pictures 
img.show()
#  Save the picture 
wordcloud.to_file("xxx.jpg")

copyright notice
author[Torres saint],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/132/202205120036302156.html

Random recommended