当前位置: 首页>>代码示例>>Python>>正文


Python WordCloud.to_image方法代码示例

本文整理汇总了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
开发者ID:s-kypr,项目名称:DataMining,代码行数:31,代码来源:wordcloud_csv.py

示例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
开发者ID:adeze,项目名称:topic_space,代码行数:10,代码来源:app.py

示例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,")
开发者ID:fle-internal,项目名称:content-curation,代码行数:30,代码来源:export_writer.py

示例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
开发者ID:gasongjian,项目名称:reportgen,代码行数:37,代码来源:report.py

示例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')
开发者ID:shispt,项目名称:wordcloud_web,代码行数:31,代码来源:main.py

示例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()
开发者ID:hatappo,项目名称:command_history_wordcloud,代码行数:9,代码来源:command_history_wordcloud.py

示例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
开发者ID:mingkai1688,项目名称:hello-python,代码行数:36,代码来源:hello.py

示例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()
开发者ID:odinlake,项目名称:tstp,代码行数:29,代码来源:make_wordcloud.py

示例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
开发者ID:ryee1,项目名称:twittersearcherproject,代码行数:10,代码来源:views.py

示例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)
开发者ID:birolkuyumcu,项目名称:twitterMonitor,代码行数:10,代码来源:twitterMonitor.py

示例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')
开发者ID:calthoff,项目名称:tstp,代码行数:11,代码来源:bringing_it_all_together.py

示例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
开发者ID:NTU-SCSE,项目名称:pdf-server,代码行数:59,代码来源:service.py

示例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)
开发者ID:NotSoSuper,项目名称:NotSoBot,代码行数:12,代码来源:Wc.py

示例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"))
开发者ID:ibm-cds-labs,项目名称:pixiedust_learning,代码行数:21,代码来源:display.py

示例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
开发者ID:billypease,项目名称:text-mining-the-office,代码行数:12,代码来源:text-mining-the-office.py


注:本文中的wordcloud.WordCloud.to_image方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。