本文整理汇总了Python中wordcloud.WordCloud.to_image方法的典型用法代码示例。如果您正苦于以下问题:Python WordCloud.to_image方法的具体用法?Python WordCloud.to_image怎么用?Python WordCloud.to_image使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类wordcloud.WordCloud
的用法示例。
在下文中一共展示了WordCloud.to_image方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: wordcloud
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_image [as 别名]
def wordcloud(datafile):
#remove stop words, the most common words in a language
vectorizer=CountVectorizer(stop_words='english')
for word in vectorizer.get_stop_words():
STOPWORDS.add(word)
STOPWORDS.add("said")
pony_mask = np.array(Image.open("../pinkyB.jpg"))
wc = WordCloud(background_color="black", max_words=2000, mask=pony_mask, stopwords=STOPWORDS)
#init dictionary with the five categories
categoriesSet = set(datafile["Category"])
categoriesDict = dict.fromkeys(categoriesSet,"")
#Conditional Selection
# business = datafile.ix[datafile["Category"]=="Business"]
# print business["Content"].size
#fill index with data from cv
for index, row in datafile.iterrows():
categoriesDict[row["Category"]] += str(row["Content"])
for category, text in categoriesDict.iteritems():
wc.generate(text)
image = wc.to_image()
image.save("../wordcloud/wordcloud_" + category + ".jpg")
return
示例2: get_wordcloud_img
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_image [as 别名]
def get_wordcloud_img(self, interval_id):
text_freq = self.get_word_frequencies(interval_id)
wordcloud = WordCloud(font_path=FONT_PATH, width=self.image_width, height=int(self.image_width * .75))
wordcloud.fit_words(list(reversed(text_freq[-100:])))
img_io = StringIO()
wordcloud.to_image().save(img_io, 'JPEG', quality=70)
img_io.seek(0)
return img_io
示例3: get_tagcloud
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_image [as 别名]
def get_tagcloud(self, tags, tag_limit=None):
tag_limit = tag_limit or len(tags)
tags = sorted(tags, key=lambda kv: -kv['count'])[:tag_limit] # Get top X tags
tag_dict = {t['tag_name']: t['count'] for t in tags}
# Generate a word cloud image
wordcloud = WordCloud(
background_color='white',
min_font_size=10,
max_font_size=60,
width=self.tagcloud_width,
height=self.tagcloud_height or 30 * len(tags) / 2 + 10,
font_path=os.path.sep.join([settings.STATIC_ROOT, 'fonts', 'OpenSans-Regular.ttf'])
).generate_from_frequencies(tag_dict)
tag_counts = [t['count'] for t in tags]
step = (float(max(tag_counts))) / len(self.color_selection)
thresholds = list(reversed([int(round(i * step)) for i in range(len(self.color_selection))]))
def get_color(word, font_size, position, orientation, random_state=None, **kwargs):
index = next((i for i, t in enumerate(thresholds) if tag_dict[word] >= t), 0)
return self.color_selection[index]
wordcloud.recolor(color_func=get_color)
image = wordcloud.to_image()
filepath = self.get_write_to_path(ext="png")
image.save(filepath)
return encode_file_to_base64(filepath, "data:image/png;base64,")
示例4: genwordcloud
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_image [as 别名]
def genwordcloud(texts,mask=None,font_path=None,background_color='white'):
'''生成词云
parameter
----------
mask: RGBA模式数组,最后一个分量是alpha通道, 默认会生成一个900*1200的椭圆
font_path: 采用的字体,建议采用安卓默认字体DroidSansFallback.ttf
return
-------
img:可以直接img.save('test.png')
'''
from PIL import Image
try:
from wordcloud import WordCloud
except:
#raise Exception('wordcloud need install wordcloud package.')
print('wordcloud need install wordcloud package.')
return None
if mask is None:
tmp=np.zeros((900,1200),dtype=np.uint8)
for i in range(tmp.shape[0]):
for j in range(tmp.shape[1]):
if (i-449.5)**2/(430**2)+(j-599.5)**2/(580**2)>1:
tmp[i,j]=255
mask=np.zeros((900,1200,4),dtype=np.uint8)
mask[:,:,0]=tmp
mask[:,:,1]=tmp
mask[:,:,2]=tmp
mask[:,:,3]=255
else:
mask=np.array(Image.open(mask))
wordcloud = WordCloud(background_color = background_color,font_path=font_path, mask = mask)
wordcloud.generate(texts)
img=wordcloud.to_image()
return img
示例5: main
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_image [as 别名]
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--url', metavar='URL', required=True, help='input the url')
args = parser.parse_args()
url = args.url
output_file = path.join(path.dirname(__file__), 'wordcloud.png')
response = requests.get(url)
origin_text = response.text
origin_text = re.sub(r'<script.*?>.*?</script>', '', origin_text, flags=re.I|re.M|re.DOTALL)
origin_text = re.sub(r'<style.*?>.*?</style>', '', origin_text, flags=re.I|re.M|re.DOTALL)
doc = html.fromstring(origin_text)
text = doc.xpath('//body//text()')
text = [i.strip() for i in text if i.strip()]
text = ' '.join(text)
seg = jieba.cut(text)
seg = [i.strip() for i in seg if i.strip() and not i.strip().isdigit() and i.strip() not in stopwords]
seg = ' '.join(seg)
wordcloud = WordCloud(font_path='simhei.ttf', background_color='black', margin=5, width=1800, height=800)
wordcloud = wordcloud.generate(seg)
image = wordcloud.to_image()
with open(output_file, 'wb') as f:
image.save(f, format='png')
示例6: create_wordcloud
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_image [as 别名]
def create_wordcloud(frequencies, stop_words):
if len(frequencies) == 0: Exception("No history is found.")
logger.debug("word frequencies count = %s" % len(frequencies))
logger.debug("stop words = %s" % pformat(stop_words))
wordcloud = WordCloud(background_color="black", width=900, height=600, stopwords=stop_words).generate_from_frequencies(frequencies)
image = wordcloud.to_image()
image.show()
示例7: twittersearch
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_image [as 别名]
def twittersearch():
api = twitter.Api(
consumer_key=twitter_consumer_key,
consumer_secret=twitter_consumer_secret,
access_token_key=twitter_access_token_key,
access_token_secret=twitter_access_token_secret
)
search = api.GetSearch(term='DevOps', lang='en', result_type='recent', count=100, max_id='')
item = 0
to_wordcloud = ''
to_display = '<html><body bgcolor="#0033FF"><font color="white"> <h2>Tweets about DevOps.... or <a href="'+my_url+'">click here to go back</a></h2>'
to_display += '<ol>'
for t in search:
item += 1
#to_display += str(item) + '. '
to_display += '<li>'
to_display += t.user.screen_name
to_display += ' ('
to_display += t.created_at
to_display += ') : '
to_display += t.text
to_wordcloud += t.text
to_display += '</li>'
# Generate a word cloud image
#wordcloud = WordCloud().generate(to_wordcloud)
wordcloud = WordCloud(max_font_size=40, relative_scaling=.5).generate(to_wordcloud)
wcimage = wordcloud.to_image()
random_name = 'static/'+str(random.randint(0,888888))+'-image-wc.png'
wcimage.save('./'+random_name)
to_display += '</ol></font>'
to_display += '<center><img src="/'+random_name+'" width="80%" height="80%"></center></body></html>'
return to_display
示例8: main
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_image [as 别名]
def main():
#d = path.dirname(__file__)
width, height = 1000, 500
themes = lib.datastats.themes_with_usage()
data = {
th: len(tobj.stories) ** 0.5
for th, tobj in themes.iteritems()
}
#mask = np.array(Image.open(path.join(d, "ellipse1000x500.png")))
mask = np.array(Image.open("ellipse1000x500.png"))
wordcloud = WordCloud(
font_path = 'Helvetica.ttf',
max_words = 5000,
max_font_size = 20,
prefer_horizontal = 1.0,
width = width,
height = height,
scale = 2,
mask = mask,
relative_scaling = 1.0,
).fit_words(data)
for rec in wordcloud.layout_:
print rec
image = wordcloud.to_image()
image.show()
示例9: getwordcloud
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_image [as 别名]
def getwordcloud(request):
text = request.session['words']
wordcloud = WordCloud().generate(text)
image = wordcloud.to_image()
response = HttpResponse(content_type="image/png")
image.save(response, "PNG")
return response
示例10: showWordCloud
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_image [as 别名]
def showWordCloud(self):
wordcloud = WordCloud(width=800, height=400).generate(self.fullText)
img = np.array(wordcloud.to_image())
height, width, byteValue = img.shape
byteValue = byteValue * width
image = QtGui.QImage(img.data, width, height, byteValue, QtGui.QImage.Format_RGB888)
pxmp = QtGui.QPixmap(image)
self.label.setPixmap(pxmp)
示例11: create_wordcloud
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_image [as 别名]
def create_wordcloud(wiki_url, file_name, tag, tag_name):
""" Takes a url for a lyrics page of lyrics.wikia.com and creates a wordcloud from the lyrics.
:param wiki_url: string lyrics.wikia lyrics url e.g. http://lyrics.wikia.com/wiki/The_Beatles:Girl.
"""
lyrics = get_lyrics(wiki_url, tag, tag_name)
wordcloud = WordCloud().generate(lyrics)
image = wordcloud.to_image()
image.show()
image.save(path.dirname(__file__) + '/wordcloud.jpg')
示例12: recursive_extract
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_image [as 别名]
def recursive_extract(node, source, target, parent_section, book):
print('[Info] Processing "' + node['title'] + '"')
accumulated_text = ''
# check if has children
has_children = len(node[CHILDREN]) != 0
# create Section entry
section = Section.objects.create(book=book, title=node[TITLE], slugified=node[SLUGIFIED],
has_children=has_children)
section.save()
# create Adjacency entry
if parent_section is not None:
adjacency = Adjacency.objects.create(parent=parent_section, child=section)
adjacency.save()
else:
section.title = book.title
section.save()
book.root_section = section
book.save()
# if the current node have children
if has_children:
target = os.path.join(target, node[SLUGIFIED])
# create target directory
if not os.path.exists(target):
os.mkdir(target)
# loop through children and do recursion
for child in node[CHILDREN]:
child_text = recursive_extract(child, source, target, section, book)
accumulated_text += child_text
# save content of the current node
with open(os.path.join(target, node[SLUGIFIED] + '.txt'), 'w+') as file:
plain_text = extract_plain_text(os.path.join(source, node['link']))
file.write(plain_text)
# create base64 encoded word cloud image in Adjacency entry
accumulated_text += plain_text
if accumulated_text != '':
wordcloud = WordCloud(width=1024, height=768).generate(accumulated_text)
image = wordcloud.to_image()
buffered = BytesIO()
image.save(buffered, format='JPEG')
base64_encoded = base64.b64encode(buffered.getvalue())
section.word_cloud_base64 = str(base64_encoded, 'ascii')
else:
section.word_cloud_base64 = NO_CONTENT_BASE64
section.save()
# return accumulated text
return accumulated_text
示例13: make_wc
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_image [as 别名]
def make_wc(self, text, max):
try:
wc = WordCloud(background_color='black', width=1024, height=768, max_words=max).generate(' '.join(text))
img = wc.to_image()
b = BytesIO()
img.save(b, 'png')
b.seek(0)
return b
except Exception as e:
return str(e)
示例14: doRender
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_image [as 别名]
def doRender(self,handlerId):
# convert from dataframe to dict
dfdict = {}
df = self.entity.toPandas()
for x in range(len(df)):
currentid = df.iloc[x,0] or 'NoStreet'
currentvalue = df.iloc[x,1]
dfdict.setdefault(currentid, 0)
dfdict[currentid] = dfdict[currentid] + currentvalue
# create word cloud from dict
wc = WordCloud(background_color="white").fit_words(dfdict)
# encode word cloud image to base64 string
b = cStringIO.StringIO()
wc.to_image().save(b, format="PNG")
img_str = base64.b64encode(b.getvalue())
self._addHTMLTemplate("wordcloud.html", base64image=img_str.decode("ascii"))
示例15: make_cloud_tag
# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_image [as 别名]
def make_cloud_tag(text):
# Generate a word cloud image
wordcloud = WordCloud().generate(text)
# take relative word frequencies into account, lower max_font_size
wordcloud = WordCloud(background_color='white', width=600, height = 400,
max_font_size=60, relative_scaling=.5).generate(text)
# display image the pil way
image = wordcloud.to_image()
image.show()
return