我在 python 中使用 Wordcloud packge 直接从文本文件生成词云。 这是我从 stckoverflow 重新使用的代码:
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 ("xyz.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,interpolation="bilinear")
plt.axis('off')
plt.show()
它给我一个词云。 WordCloud() 函数中是否有任何参数可以在不格式化文本文件的情况下传递 n-gram。
我想要bigram的词云。或显示时带有下划线的单词。喜欢: machine_learning(机器和学习是两个不同的词)
请您参考如下方法:
二元词云可以很容易地通过降低词云中的 collocation_threshold 参数的值来生成。
编辑词云:
wordcloud = WordCloud(font_path = r'C:\Windows\Fonts\Verdana.ttf',
stopwords = STOPWORDS,
background_color = 'white',
width = 1200,
height = 1000,
color_func = random_color_func,
collocation_threshold = 3 --added this to your question code, try changing this value between 1-50
).generate(file_content)
更多信息:
collocation_threshold: int, default=30 Bigrams must have a Dunning likelihood collocation score greater than this parameter to be counted as bigrams. Default of 30 is arbitrary.
您还可以在此处找到 wordcloud.WordCloud 的源代码:https://amueller.github.io/word_cloud/_modules/wordcloud/wordcloud.html
