本文整理汇总了Python中wordcloud.WordCloud方法的典型用法代码示例。如果您正苦于以下问题:Python wordcloud.WordCloud方法的具体用法?Python wordcloud.WordCloud怎么用?Python wordcloud.WordCloud使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类wordcloud
的用法示例。
在下文中一共展示了wordcloud.WordCloud方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_wordcloud
# 需要导入模块: import wordcloud [as 别名]
# 或者: from wordcloud import WordCloud [as 别名]
def generate_wordcloud(df, save_cfg=cfg.saving_config):
brain_mask = np.array(Image.open("./img/brain_stencil.png"))
def transform_format(val):
if val == 0:
return 255
else:
return val
text = (df['Title']).to_string()
stopwords = set(STOPWORDS)
stopwords.add("using")
stopwords.add("based")
wc = WordCloud(
background_color="white", max_words=2000, max_font_size=50, mask=brain_mask,
stopwords=stopwords, contour_width=1, contour_color='steelblue')
wc.generate(text)
# store to file
if save_cfg is not None:
fname = os.path.join(save_cfg['savepath'], 'DL-EEG_WordCloud')
wc.to_file(fname + '.' + save_cfg['format']) #, **save_cfg)
示例2: test_write_wordclouds_to_folder
# 需要导入模块: import wordcloud [as 别名]
# 或者: from wordcloud import WordCloud [as 别名]
def test_write_wordclouds_to_folder(tmpdir):
try:
import lda
import PIL
from wordcloud import WordCloud
except ImportError:
pytest.skip('at least one of lda, Pillow, wordcloud not installed')
path = tmpdir.mkdir('wordclouds').dirname
data = model_io.load_ldamodel_from_pickle('tests/data/tiny_model_reuters_5_topics.pickle')
model = data['model']
vocab = data['vocab']
phi = model.topic_word_
assert phi.shape == (5, len(vocab))
topic_word_clouds = visualize.generate_wordclouds_for_topic_words(phi, vocab, 10)
visualize.write_wordclouds_to_folder(topic_word_clouds, path, 'cloud_{label}.png')
for label in topic_word_clouds.keys():
assert os.path.exists(os.path.join(path, 'cloud_{label}.png'.format(label=label)))
示例3: generate_wordclouds_for_topic_words
# 需要导入模块: import wordcloud [as 别名]
# 或者: from wordcloud import WordCloud [as 别名]
def generate_wordclouds_for_topic_words(topic_word_distrib, vocab, top_n, topic_labels='topic_{i1}', which_topics=None,
return_images=True, **wordcloud_kwargs):
"""
Generate wordclouds for the top `top_n` words of each topic in `topic_word_distrib`.
:param topic_word_distrib: topic-word distribution; shape KxM, where K is number of topics, M is vocabulary size
:param vocab: vocabulary array of length M
:param top_n: number of top values to take from each row of `distrib`
:param topic_labels: labels used for each row; determine keys in in result dict; either single format string with
placeholders ``"{i0}"`` (zero-based topic index) or ``"{i1}"`` (one-based topic index), or
list of topic label strings
:param which_topics: if not None, a sequence of indices into rows of `topic_word_distrib` to select only these
topics to generate wordclouds from
:param return_images: if True, store image objects instead of :class:`wordcloud.WordCloud` objects in the result
dict
:param wordcloud_kwargs: pass additional options to :class:`wordcloud.WordCloud`; updates options in
:data:`~tmtoolkit.topicmod.visualize.DEFAULT_WORDCLOUD_KWARGS`
:return: dict mapping row labels to wordcloud images or instances generated from each topic
"""
return generate_wordclouds_from_distribution(topic_word_distrib, row_labels=topic_labels, val_labels=vocab,
top_n=top_n, which_rows=which_topics, return_images=return_images,
**wordcloud_kwargs)
示例4: lyrics
# 需要导入模块: import wordcloud [as 别名]
# 或者: from wordcloud import WordCloud [as 别名]
def lyrics():
with open('lyrics.json', 'r', encoding='utf-8') as f:
data = json.load(f)
tokens = list()
for v in data.values():
# 斷詞後的結果, 若非空白且長度為 2 以上, 則列入詞庫
tokens += [seg for seg in jieba.cut(v) if seg.split() and len(seg) > 1]
# 計算 tokens 內各詞彙的出現次數
counter = Counter(tokens)
print(counter.most_common(10))
# 文字雲, 要顯示中文需附上字型檔
wcloud = WordCloud(font_path='NotoSansMonoCJKtc-Regular.otf').generate(' '.join(tokens))
plt.imshow(wcloud)
plt.axis('off')
plt.show()
示例5: run
# 需要导入模块: import wordcloud [as 别名]
# 或者: from wordcloud import WordCloud [as 别名]
def run(db, args):
if platform.system() == "Darwin":
mpl.use("TkAgg")
import matplotlib.pyplot as plt
title = "Top reused passwords for {}".format(args.domain)
passwords = db.all_passwords
wc = WordCloud(background_color="black", width=1280, height=800, margin=5, max_words=1000, color_func=__get_password_color(passwords))
wc.generate(" ".join([password for password, score in passwords]))
plt.title(title)
plt.imshow(wc, interpolation="nearest", aspect="equal")
plt.axis("off")
plt.show()
示例6: generate_word_cloud
# 需要导入模块: import wordcloud [as 别名]
# 或者: from wordcloud import WordCloud [as 别名]
def generate_word_cloud():
"""
生成词云
:return:
"""
with open(filename, 'r') as f:
word_content = f.read()
# 使用jieba去分割
wordlist = jieba.cut(word_content, cut_all=True)
wl_space_split = " ".join(wordlist)
font = r'/Users/xingag/Library/Fonts/SimHei.ttf'
wordcloud = WordCloud(font_path=font, width=1080, height=1920, margin=2).generate(wl_space_split)
# 显示图片
plt.imshow(wordcloud)
plt.axis("off")
# 按照设置保存到本地文件夹
wordcloud.to_file("./output.png")
示例7: create_wordcloud
# 需要导入模块: import wordcloud [as 别名]
# 或者: from wordcloud import WordCloud [as 别名]
def create_wordcloud(content,image='weibo.jpg',max_words=5000,max_font_size=50):
cut_text = " ".join(content)
cloud = WordCloud(
# 设置字体,不指定就会出现乱码
font_path="HYQiHei-25J.ttf",
# 允许最大词汇
max_words=max_words,
# 设置背景色
# background_color='white',
# 最大号字体
max_font_size=max_font_size
)
word_cloud = cloud.generate(cut_text)
word_cloud.to_file(image)
# 分词并去除停用词
示例8: gen_img
# 需要导入模块: import wordcloud [as 别名]
# 或者: from wordcloud import WordCloud [as 别名]
def gen_img(texts, img_file):
data = ' '.join(text for text in texts)
image_coloring = imread(img_file)
wc = WordCloud(
background_color='white',
mask=image_coloring,
font_path='/Library/Fonts/STHeiti Light.ttc'
)
wc.generate(data)
# plt.figure()
# plt.imshow(wc, interpolation="bilinear")
# plt.axis("off")
# plt.show()
wc.to_file(img_file.split('.')[0] + '_wc.png')
示例9: show_wordCloud
# 需要导入模块: import wordcloud [as 别名]
# 或者: from wordcloud import WordCloud [as 别名]
def show_wordCloud(word_freq):
"""
词云显示
"""
font = r'C:\Windows\Fonts\msyh.ttc' # 指定字体,不指定会报错
color_mask = imread("resource/timg.jpg") # 读取背景图片
wcloud = WordCloud(
font_path=font,
# 背景颜色
background_color="white",
# 词云形状
mask=color_mask,
# 允许最大词汇
max_words=2000,
# 最大号字体
max_font_size=80)
wcloud.generate_from_frequencies(dict(word_freq))
# 以下代码显示图片
plt.imshow(wcloud)
plt.axis("off")
plt.show()
wcloud.to_file("data/wcimage/雪中_1.png")
示例10: show_wordCloud
# 需要导入模块: import wordcloud [as 别名]
# 或者: from wordcloud import WordCloud [as 别名]
def show_wordCloud(word_freq):
"""
词云显示
"""
font = r'C:\Windows\Fonts\msyh.ttc' # 指定字体,不指定会报错
color_mask = imread("resource/timg.jpg") # 读取背景图片
wcloud = WordCloud(
font_path=font,
# 背景颜色
background_color="white",
# 词云形状
mask=color_mask,
# 允许最大词汇
max_words=2000,
# 最大号字体
max_font_size=80)
wcloud.generate_from_frequencies(dict(word_freq))
# 以下代码显示图片
plt.imshow(wcloud)
plt.axis("off")
plt.show()
wcloud.to_file("data/wcimage/三体词云_3.png")
示例11: show_wordCloud
# 需要导入模块: import wordcloud [as 别名]
# 或者: from wordcloud import WordCloud [as 别名]
def show_wordCloud(word_freq):
"""
词云显示
"""
font = r'C:\Windows\Fonts\msyh.ttc' # 指定字体,不指定会报错
color_mask = imread("resource/timg.jpg") # 读取背景图片
wcloud = WordCloud(
font_path=font,
# 背景颜色
background_color="white",
# 词云形状
mask=color_mask,
# 允许最大词汇
max_words=2000,
# 最大号字体
max_font_size=80)
wcloud.generate_from_frequencies(dict(word_freq))
# 以下代码显示图片
plt.imshow(wcloud)
plt.axis("off")
plt.show()
wcloud.to_file("data/wcimage/三体词云_3.png")
示例12: main
# 需要导入模块: import wordcloud [as 别名]
# 或者: from wordcloud import WordCloud [as 别名]
def main():
seg = Seg()
doc = '''自然语言处理: 是人工智能和语言学领域的分支学科。
在这此领域中探讨如何处理及运用自然语言;自然语言认知则是指让电脑“懂”人类的语言。
自然语言生成系统把计算机数据转化为自然语言。自然语言理解系统把自然语言转化为计算机程序更易于处理的形式。'''
# res = seg.seg_from_doc(doc)
datalist = seg.get_data_from_mysql(1000, 0)
keywords = dict(seg.get_keyword_from_datalist(datalist))
font_path = root_path + '/data/simfang.ttf'
bg_path = root_path + '/data/bg.jpg'
#back_color = np.array(Image.open(bg_path))
back_color = imread(bg_path)
image_colors = ImageColorGenerator(back_color)
wordcloud = WordCloud(font_path=font_path, background_color="white", mask=back_color,
max_words=2000, max_font_size=100, random_state=48, width=1000, height=800, margin=2)
wordcloud.generate_from_frequencies(keywords)
plt.figure()
plt.imshow(wordcloud.recolor(color_func=image_colors))
plt.axis("off")
plt.show()
wordcloud.to_file(root_path + '/data/pic2.png')
示例13: PrintWorfCloud
# 需要导入模块: import wordcloud [as 别名]
# 或者: from wordcloud import WordCloud [as 别名]
def PrintWorfCloud(self,documents,backgroundImgPath,fontPath):
'''Print out the word cloud of all news(articles/documents).
# Arguments:
documents: Overall raw documents.
backgroundImgPath: Background image path.
fontPath: The path of windows fonts that used to create the word-cloud.
'''
from scipy.misc import imread
import matplotlib.pyplot as plt
from wordcloud import WordCloud
corpora_documents = self.jieba_tokenize(documents) #分词
for k in range(len(corpora_documents)):
corpora_documents[k] = ' '.join(corpora_documents[k])
corpora_documents = ' '.join(corpora_documents)
color_mask = imread(backgroundImgPath) #"C:\\Users\\lenovo\\Desktop\\Text_Mining\\3.jpg"
cloud = WordCloud(font_path=fontPath,mask=color_mask,background_color='white',\
max_words=2000,max_font_size=40) #"C:\\Windows\\Fonts\\simhei.ttf"
word_cloud = cloud.generate(corpora_documents)
plt.imshow(word_cloud, interpolation='bilinear')
plt.axis("off")
示例14: draw_word_cloud
# 需要导入模块: import wordcloud [as 别名]
# 或者: from wordcloud import WordCloud [as 别名]
def draw_word_cloud(content):
d = os.path.dirname(__file__)
img = Image.open(os.path.join(d, "changzuoren.jpg"))
width = img.width / 80
height = img.height / 80
alice_coloring = np.array(img)
my_wordcloud = WordCloud(background_color="white",
max_words=500, mask=alice_coloring,
max_font_size=200, random_state=42,
font_path=(os.path.join(d, "../common/font/PingFang.ttc")))
my_wordcloud = my_wordcloud.generate_from_frequencies(content)
image_colors = ImageColorGenerator(alice_coloring)
plt.figure(figsize=(width, height))
plt.imshow(my_wordcloud.recolor(color_func=image_colors))
plt.imshow(my_wordcloud)
plt.axis("off")
# 通过设置subplots_adjust来控制画面外边框
plt.subplots_adjust(bottom=.01, top=.99, left=.01, right=.99)
plt.savefig("changzuoren_wordcloud.png")
plt.show()
示例15: draw_word_cloud
# 需要导入模块: import wordcloud [as 别名]
# 或者: from wordcloud import WordCloud [as 别名]
def draw_word_cloud(content):
d = os.path.dirname(__file__)
img = Image.open(os.path.join(d, "toutiao.jpg"))
width = img.width / 80
height = img.height / 80
alice_coloring = np.array(img)
my_wordcloud = WordCloud(background_color="white",
max_words=500, mask=alice_coloring,
max_font_size=200, random_state=42,
font_path=(os.path.join(d, "../common/font/PingFang.ttc")))
my_wordcloud = my_wordcloud.generate_from_frequencies(content)
image_colors = ImageColorGenerator(alice_coloring)
plt.figure(figsize=(width, height))
plt.imshow(my_wordcloud.recolor(color_func=image_colors))
plt.imshow(my_wordcloud)
plt.axis("off")
# 通过设置subplots_adjust来控制画面外边框
plt.subplots_adjust(bottom=.01, top=.99, left=.01, right=.99)
plt.savefig("toutiao_wordcloud.png")
plt.show()