簡體   English   中英

來自 txt 文件的 Python Wordcloud

[英]Python Wordcloud from a txt file

我正在嘗試使用 txt 文件中的文本創建 wordcloud。

到目前為止,這是我的代碼

import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS


file_content=open ("tweets.txt").read()



wordcloud = WordCloud(font_path = 'C:\Windows\Fonts\Verdana.tff',
                            stopwords=STOPWORDS,
                            background_color = 'white',
                            width=1200,
                            height=1000
                            ).generate(file_content)

plt.imshow(wordcloud)
plt.axis('off')
plt.show()

運行此代碼后顯示的錯誤是:

 File "WordCloud.py", line 14, in <module>
    ).generate(file_content)
  File "C:\Python27\lib\site-packages\wordcloud\wordcloud.py", line 448, in generate
    return self.generate_from_text(text)
  File "C:\Python27\lib\site-packages\wordcloud\wordcloud.py", line 434, in generate_from_text
    self.generate_from_frequencies(words)
  File "C:\Python27\lib\site-packages\wordcloud\wordcloud.py", line 317, in generate_from_frequencies
    font = ImageFont.truetype(self.font_path, font_size)
  File "C:\Python27\lib\site-packages\PIL\ImageFont.py", line 238, in truetype
    return FreeTypeFont(font, size, index, encoding)
  File "C:\Python27\lib\site-packages\PIL\ImageFont.py", line 127, in __init__
    self.font = core.getfont(font, size, index, encoding)
IOError: cannot open resource

獎金問題:如何更改文本顏色?

如前所述,將您的字體更改為ttf但我建議您還使用r作為前綴,以避免任何意外的反斜杠轉義。

要添加您自己的配色方案,您需要添加一個顏色回調函數,例如random_color_func 這個是用隨機 L 和固定 H 和 S 構建 HSL 類型的顏色。

import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS


def random_color_func(word=None, font_size=None, position=None, orientation=None, font_path=None, random_state=None):
    h = int(360.0 * 45.0 / 255.0)
    s = int(100.0 * 255.0 / 255.0)
    l = int(100.0 * float(random_state.randint(60, 120)) / 255.0)

    return "hsl({}, {}%, {}%)".format(h, s, l)

file_content=open ("tweets.txt").read()

wordcloud = WordCloud(font_path = r'C:\Windows\Fonts\Verdana.ttf',
                            stopwords = STOPWORDS,
                            background_color = 'white',
                            width = 1200,
                            height = 1000,
                            color_func = random_color_func
                            ).generate(file_content)

plt.imshow(wordcloud)
plt.axis('off')
plt.show()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM