Python制作詞云的代碼怎么寫

本文將為您詳細解讀如何用python編寫生成詞云的代碼,希望您閱讀完后能有所收益。

導入所需的庫

import numpy as np import pandas as pd from PIL import Image from wordcloud import WordCloud, STOPWORDS

讀取文本數據

text = "你的文本數據"

創建詞云對象

# 設定詞云參數 wordcloud = WordCloud(     width=800,  # 設置寬度     height=600,  # 設置高度     background_color="white",  # 背景色設為白色     stopwords=STOPWORDS,  # 使用預設的停用詞列表     max_words=200,  # 最大顯示詞數為200 ).generate(text)

生成詞云圖

立即學習Python免費學習筆記(深入)”;

wordcloud.to_file("wordcloud.png")  # 將詞云保存為文件

自定義詞云形狀

# 讀取形狀圖像 mask = np.array(Image.open("shape.png")) <h1>生成帶有特定形狀的詞云對象</h1><p>wordcloud = WordCloud( width=800, height=600, background_color="white", mask=mask,  # 使用形狀作為掩碼 max_words=200, ).generate(text)</p><h1>生成詞云</h1><p>wordcloud.to_file("wordcloud_shaped.png")

應用字體和顏色

# 設定字體 font_path = "path/to/font.ttf" wordcloud = WordCloud( font_path=font_path, ).generate(text) wordcloud.to_file("wordcloud_with_font.png")</p><h1>設定顏色圖</h1><p>color_map = "path/to/color_map.png" wordcloud = WordCloud( colormap=color_map, ).generate(text) wordcloud.to_file("wordcloud_with_color_map.png")

處理非英語文本

# 對非英語文本使用自定義停用詞列表 stopwords = ["word1", "word2", "word3"] wordcloud = WordCloud( stopwords=stopwords, ).generate(text) wordcloud.to_file("wordcloud_with_custom_stopwords.png")</p><h1>使用正則表達式過濾非英語單詞</h1><p>import re regex = r"[^ws]" text = re.sub(regex, "", text) wordcloud = WordCloud().generate(text) wordcloud.to_file("wordcloud_non_english.png")

高級選項

  • collocations: 允許詞對同時顯示
  • max_font_size: 設定最大字體大小
  • scale: 調整詞云的縮放比例
  • contour_width: 設定輪廓寬度
  • contour_color: 設定輪廓顏色

以上內容詳細介紹了如何用python編寫生成詞云的代碼。如需更多相關內容,請訪問編程學習網查看其它文章!

Python制作詞云的代碼怎么寫

? 版權聲明
THE END
喜歡就支持一下吧
點贊11 分享