本文整理汇总了Python中wordcloud.WordCloud.to_file方法的典型用法代码示例。如果您正苦于以下问题:Python WordCloud.to_file方法的具体用法?Python WordCloud.to_file怎么用?Python WordCloud.to_file使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类wordcloud.WordCloud
的用法示例。
在下文中一共展示了WordCloud.to_file方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_word_cloud
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_file [as 别名]
def generate_word_cloud(img_bg_path,top_words_with_freq,font_path,to_save_img_path,background_color = 'white'):
# 读取背景图形
img_bg = imread(img_bg_path)
# 创建词云对象
wc = WordCloud(font_path = font_path, # 设置字体
background_color = background_color, # 词云图片的背景颜色,默认为白色
max_words = 500, # 最大显示词数为1000
mask = img_bg, # 背景图片蒙版
max_font_size = 50, # 字体最大字号
random_state = 30, # 字体的最多模式
width = 1000, # 词云图片宽度
margin = 5, # 词与词之间的间距
height = 700) # 词云图片高度
# 用top_words_with_freq生成词云内容
wc.generate_from_frequencies(top_words_with_freq)
# 用matplotlib绘出词云图片显示出来
plt.imshow(wc)
plt.axis('off')
plt.show()
# 如果背景图片颜色比较鲜明,可以用如下两行代码获取背景图片颜色函数,然后生成和背景图片颜色色调相似的词云
#img_bg_colors = ImageColorGenerator(img_bg)
#plt.imshow(wc.recolor(color_func = img_bg_colors))
# 将词云图片保存成图片
wc.to_file(to_save_img_path)
示例2: word_cloud
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_file [as 别名]
def word_cloud(csv_file, stopwords_path, pic_path):
pic_name = csv_file+"_词云图.png"
path = os.path.abspath(os.curdir)
csv_file = path+ "\\" + csv_file + ".csv"
csv_file = csv_file.replace('\\', '\\\\')
d = pd.read_csv(csv_file, engine='python', encoding='utf-8')
content = []
for i in d['content']:
try:
i = translate(i)
except AttributeError as e:
continue
else:
content.append(i)
comment_after_split = jieba.cut(str(content), cut_all=False)
wl_space_split = " ".join(comment_after_split)
backgroud_Image = plt.imread(pic_path)
stopwords = STOPWORDS.copy()
with open(stopwords_path, 'r', encoding='utf-8') as f:
for i in f.readlines():
stopwords.add(i.strip('\n'))
f.close()
wc = WordCloud(width=1024, height=768, background_color='white',
mask=backgroud_Image, font_path="C:\simhei.ttf",
stopwords=stopwords, max_font_size=400,
random_state=50)
wc.generate_from_text(wl_space_split)
img_colors = ImageColorGenerator(backgroud_Image)
wc.recolor(color_func=img_colors)
plt.imshow(wc)
plt.axis('off')
plt.show()
wc.to_file(pic_name)
示例3: generateWordCloud
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_file [as 别名]
def generateWordCloud(node, contribs, wordsToShow=None, normalize=True, normMin=0, normMax=1):
contrib = contribs[node]
if (normalize):
contrib = normalizeContrib(contrib, normMin, normMax)
# generate text
text = generateText(contrib, wordsToShow)
# load mask
d = path.dirname(__file__)
circle_mask = imread(path.join(d, "black_circle_mask_whitebg.png"))
# gen word cloud
wc = WordCloud(background_color="white", max_words=2000, mask=circle_mask)
wc.generate(text)
# store to file
wc.to_file(path.join(d, "node.png"))
# show
useColorFunc = False #normalize
if (useColorFunc):
plt.imshow(wc.recolor( color_func=pos_neg_color_func ))
else:
plt.imshow(wc)
plt.axis("off")
plt.show()
示例4: generate_wc
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_file [as 别名]
def generate_wc(self, background_color='#ffffff'):
"""generate wordcloud and save to file"""
# fig_kw = dict(figsize=(self.width/self.dpi, self.height/self.dpi),
# dpi=self.dpi)
self.get_exclude_words()
try:
imgpath = os.path.join(self.curdir, self.wordcloud_mask)
arr = np.array(Image.open(imgpath))
# Other masks can be extracted from
# Font-Awesome (http://minimaxir.com/2016/05/wordclouds/)
# Download font or use the default one
font_path = get_font(self.font_name)
if self.allow_font_change:
logger.info('Using {} font'.format(font_path))
# print(font_path)
wc = WordCloud(width=self.width, height=self.height,
font_path=font_path, colormap=self.cmap,
stopwords=self.exclude_words,
background_color=background_color, mode='RGBA',
mask=arr).generate(self.text)
self.make_img_file()
wc.to_file(self.img_file)
self.error_in_wordcloud_gen = None
self.font_name = None # reset to default
except Exception as e:
self.error_in_wordcloud_gen = e
示例5: run
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_file [as 别名]
def run():
f = open(u'words2.txt', 'r').read()
words = list(jieba.cut(f))
a = []
for w in words:
if len(w) > 1:
a.append(w)
text = r' '.join(a)
bg = np.array(Image.open('bg.jpg'))
wordcloud = WordCloud(
background_color = 'white',
#width = 1500,
#height = 960,
#margin = 10,
mask = bg,
font_path='C:/Windows/Fonts/simkai.ttf',
).generate(text)
image_colors=ImageColorGenerator(bg)
plt.imshow(wordcloud.recolor(color_func=image_colors))
plt.axis('off')
plt.show()
wordcloud.to_file('words_result3.png')
return
示例6: wordCloud
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_file [as 别名]
def wordCloud(text_array,name,keyword=""):
new_text_arr=[]
if keyword is not "":
keyword=keyword.split(" ")[1]
for text in text_array:
if keyword in text:
new_text_arr.append(text)
text_array=new_text_arr
cloud_text=""
for text in text_array:
cloud_text+=text+" "
m_stopwords=['police','traffic','sir']
for word in m_stopwords:
STOPWORDS.add(word)
image_mask = os.path.join(BASE_DIR, 'static/tool/img/nebula.png')
coloring = imread(image_mask)
wordcloud = WordCloud(stopwords=STOPWORDS,background_color="white",mask=coloring,ranks_only=True,max_words=50).generate(cloud_text)
filename=os.path.join(BASE_DIR, 'static/tool/img/'+name+'.png')
image_colors = ImageColorGenerator(coloring)
wordcloud.recolor(color_func=image_colors)
wordcloud.to_file(filename)
data_uri = open(filename, 'rb').read().encode('base64').replace('\n', '')
img_tag = '<img src="data:image/png;base64,{0}" style="height:400px;">'.format(data_uri)
layout=wordcloud.layout_
words_colours={}
count=1
for lo in layout:
entry={}
entry['word']=lo[0][0]
color=lo[len(lo)-1]
color=color[4:]
color=color[:-1]
color_split=color.split(',')
color_num=[int(x) for x in color_split]
color_hex='#%02x%02x%02x' % tuple(color_num)
# print color_num
entry['color']=color_hex
words_colours[count]=entry
count+=1
# print words_colours
list_html=""
cap=51
if cap>len(words_colours):
cap=len(words_colours)
for i in range(1,cap):
list_html+='<li class="list-group-item" ><a class="cloud-key-'+name+'" href="#" style="color:'+words_colours[i]['color']+'">'
list_html+="#"+str(i)+" "+words_colours[i]['word']+'</a></li>'
return (img_tag,list_html)
示例7: generate_cloud
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_file [as 别名]
def generate_cloud():
d = path.dirname(__file__)
janice = open(path.join(d, 'messages.txt')).read()
group_mask = misc.imread(path.join(d, "mask.png"), flatten=True)
wc = WordCloud(background_color="white", max_words = 2000, mask=group_mask)
wc.generate(text)
wc.to_file(path.join(d, "masked.jpg"))
示例8: wordcloudplot_focus
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_file [as 别名]
def wordcloudplot_focus(self, yizhongzhazha=None, backimage=None):
"""Do wordcloud plots for contacts. need to run relationship()
first to get self._relationship.
Parameters
yizhongzhazha: pandas object by loading the data
backimage: background image file's directory
Returns: basic word cloud plots saved in files
"""
if yizhongzhazha is None:
print("Need load message table first.")
return
if self._contacts_topN is None:
print("need to run relationship() first.")
return
if backimage is not None:
custompic = imread(backimage)
else:
custompic = None
if not os.path.exists('./wordcloud'):
os.makedirs('./wordcloud')
wordcloud = WordCloud(background_color="white", mask=custompic,
max_words=2000,scale=3)
for k in range(len(self._contacts_topN)):
text=self._relationship.iloc[:,k]
text_to_wordcloud=[]
for i in range(len(text)):
text_to_wordcloud.append((text.index.values[i]+' ')*text[i])
text=''.join(text_to_wordcloud)
wordcloud.generate(text)
wordcloud.to_file("./wordcloud/"+self._relationship.columns[k]+'2.png')
示例9: make_word_cloud
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_file [as 别名]
def make_word_cloud(text, save_path, background_color='black'):
# text expected to a string or a list of [(word, count), ...]
from wordcloud import WordCloud
import os
def col_fun(word, *args, **kw):
return '#333'
if type(text) == str:
big_string = text
else:
big_string = ''
for word in text:
big_string = big_string + ''.join((word[0]+' ') * word[1])
# print 'trying to make cloud: %s' % save_path
# print os.getcwd()
wc = WordCloud(background_color=background_color,
color_func=col_fun,
max_words=10000,
height=200,
width=700,
font_path='app/static/fonts/NanumScript.ttc').generate(big_string)
wc.generate(big_string)
wc.to_file('app/%s' % save_path)
示例10: create_word_cloud
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_file [as 别名]
def create_word_cloud(filename):
# 读取文件内容
text = open("{}.txt".format(filename), encoding='utf-8').read()
# 注释部分采用结巴分词
# wordlist = jieba.cut(text, cut_all=True)
# wl = " ".join(wordlist)
# 设置词云
wc = WordCloud(
# 设置背景颜色
background_color="white",
# 设置最大显示的词云数
max_words=2000,
# 这种字体都在电脑字体中,window在C:\Windows\Fonts\下,mac下可选/System/Library/Fonts/PingFang.ttc 字体
font_path='C:\\Windows\\Fonts\\simfang.ttf',
height=500,
width=500,
# 设置字体最大值
max_font_size=60,
# 设置有多少种随机生成状态,即有多少种配色方案
random_state=30,
)
myword = wc.generate(text) # 生成词云 如果用结巴分词的话,使用wl 取代 text, 生成词云图
# 展示词云图
plt.imshow(myword)
plt.axis("off")
plt.show()
wc.to_file('signature.png') # 把词云保存下
示例11: txt2pic
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_file [as 别名]
def txt2pic(txt_file, out_png, font_path, mask_file):
text_address = path.abspath(txt_file)
text = open(text_address).read() #读取文本
text_cut = jieba.cut(text) #分词
new_textlist = ' '.join(text_cut) #组合
pic_address = path.abspath(mask_file)
pic = imread(pic_address) #读取图片
pic_color = ImageColorGenerator(pic) #根据图片生成颜色函数
wc = WordCloud(background_color='white', #构造wordcloud类
mask=pic,
width = 750,
height = 750,
max_font_size = 80,
random_state=30,
font_path=font_path,
max_words=500,
min_font_size=2,
color_func=pic_color
)
wc.generate(new_textlist) #生成词云图
plt.figure() #画图
plt.imshow(wc)
plt.axis("off")
plt.show()
wc.to_file(out_png) #保存图片
示例12: create_wordclouds
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_file [as 别名]
def create_wordclouds(self, text, name_of_cloud, additional_stop_list, max_words, width, height, bigram = False):
text_nopunc = self.remove_punctuation(text, "", "")
text_lower = text_nopunc.lower()
stop = self.stopwords
stop.extend(additional_stop_list)
text_nostop = self.remove_stopword(text_lower, stop)
tokens = wt(text_nostop)
text_lem = self.lemmatize(tokens)
tokens_lem = wt(text_lem)
my_bigrams = nltk.bigrams(tokens_lem)
if bigram:
bigram_merged=list()
for line in my_bigrams:
bigram_merged.append(line[0]+' ' + line[1])
counts = collections.Counter(bigram_merged)
else:
counts = collections.Counter(tokens_lem)
final = counts.most_common(max_words)
max_count = max(final, key=operator.itemgetter(1))[1]
final = [(name, count / float(max_count))for name, count in final]
# tags = make_tags(final, maxsize=max_word_size)
# create_tag_image(tags, name_of_cloud+'.png', size=(width, height), layout=3, fontname='Crimson Text', background = (255, 255, 255))
# temp_cloud = " ".join(text for text, count in final)
word_cloud = WordCloud(font_path="fonts/Georgia.ttf",
width=width, height=height, max_words=max_words, stopwords=stop)
word_cloud.fit_words(final)
word_cloud.to_file(name_of_cloud + ".png")
示例13: main
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_file [as 别名]
def main(save_files = False, db_filename = '../output/database.sqlite'):
conn = sqlite3.connect(db_filename)
c = conn.cursor()
# Retrieve papers
c.execute('''SELECT *
FROM Papers''')
paper_content = c.fetchall()
conn.close()
titles = ''
for pc in paper_content:
titles += pc[1]
# A Marvin Minsky mask
mask = np.array(Image.open("../files/minsky_mask.png"))
wc = WordCloud(background_color="white", max_words=2000, mask=mask, stopwords=STOPWORDS.copy())
# Generate word cloud
wc.generate(titles)
if (save_files):
# Store to file
wc.to_file("../files/title_cloud.png")
# Show word cloud
plt.imshow(wc)
plt.axis("off")
# Show mask
# plt.figure()
# plt.imshow(mask, cmap=plt.cm.gray)
# plt.axis("off")
plt.show()
示例14: makecloud
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_file [as 别名]
def makecloud(name):
cnt = 0
# file=open('age_over54_train/KABarron.txt')
file = open('extracted_tweets/'+name + ".txt")
demo_text = ""
stop = stopwords.words('english')
for line in file:
if cnt < 2:
cnt += 1
elif cnt < 52:
line = line.strip().replace("'", "").replace('"', '')
if str(line).startswith("RT"):
continue
else:
newline = [i for i in line.split() if i not in stop]
finsent = ""
for word in newline:
if "@" in word or "https" in word or ".co" in word or "http" in word:
continue
else:
finsent += word + " "
demo_text += finsent + " "
cnt += 1
else:
break
filename = 'static/'+ name + '_cloud.png'
wordcloud = WordCloud(max_font_size=500,width=900,height=600,background_color='white',prefer_horizontal=0.5,font_path="a_song_for_jennifer/a song for jennifer.ttf").generate(demo_text)
wordcloud.to_file(filename)
return str(name + '_cloud.png')
示例15: create_word_cloud
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_file [as 别名]
def create_word_cloud(filename):
text = open('{}.txt'.format(filename),encoding='utf-8').read()
print(type(text))
# print(text)
#结巴分词
wordlist = jieba.cut(text,cut_all=False)
wl = " ".join(wordlist)
#设置词云
wc = WordCloud(
#设置背景颜色
background_color='white',
#设置最大的显示词云数
max_words=2000,
#字体
font_path="../python_space/like.ttf",
height=1200,
width=1600,
#设置有多少中随机生成状态,即有多少种配色方案
random_state=30,
)
myword = wc.generate(wl)#生成词云
#展示词云
plt.imshow(myword)
plt.axis("off")
plt.show()
wc.to_file('py_book.png')#把词云保存下来