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


Python WordCloud.to_array方法代码示例

本文整理汇总了Python中wordcloud.WordCloud.to_array方法的典型用法代码示例。如果您正苦于以下问题:Python WordCloud.to_array方法的具体用法?Python WordCloud.to_array怎么用?Python WordCloud.to_array使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在wordcloud.WordCloud的用法示例。


在下文中一共展示了WordCloud.to_array方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_recolor

# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_array [as 别名]
def test_recolor():
    wc = WordCloud(max_words=50)
    wc.generate(THIS)
    array_before = wc.to_array()
    wc.recolor()
    array_after = wc.to_array()
    # check_list that the same places are filled
    assert_array_equal(array_before.sum(axis=-1) != 0,
                       array_after.sum(axis=-1) != 0)
    # check_list that they are not the same
    assert_greater(np.abs(array_before - array_after).sum(), 10000)

    # check_list that recoloring is deterministic
    wc.recolor(random_state=10)
    wc_again = wc.to_array()
    assert_array_equal(wc_again, wc.recolor(random_state=10))
开发者ID:pipilove,项目名称:TopicModel,代码行数:18,代码来源:test_wordcloud.py

示例2: make_wordle_from_mallet

# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_array [as 别名]
def make_wordle_from_mallet(word_weights_file, 
                            num_topics, 
                            words,
                            TopicRanksFile,
                            outfolder,
                            font_path, 
                            dpi):
    """
    # Generate wordles from Mallet output, using the wordcloud module.
    """
    print("\nLaunched make_wordle_from_mallet.")
    for topic in range(0,num_topics):
        ## Gets the text for one topic.
        text = get_wordlewords(words, word_weights_file, topic)
        wordcloud = WordCloud(font_path=font_path, width=1600, height=1200, background_color="white", margin=4).generate(text)
        default_colors = wordcloud.to_array()
        rank = get_topicRank(topic, TopicRanksFile)
        figure_title = "topic "+ str(topic) + " ("+str(rank)+"/"+str(num_topics)+")"       
        plt.imshow(wordcloud.recolor(color_func=get_color_scale, random_state=3))
        plt.imshow(default_colors)
        plt.imshow(wordcloud)
        plt.title(figure_title, fontsize=30)
        plt.axis("off")
        
        ## Saving the image file.
        if not os.path.exists(outfolder):
            os.makedirs(outfolder)
        figure_filename = "wordle_tp"+"{:03d}".format(topic) + ".png"
        plt.savefig(outfolder + figure_filename, dpi=dpi)
        plt.close()
    print("Done.")
开发者ID:cligs,项目名称:projects,代码行数:33,代码来源:visualize.py

示例3: plotTwiiterWordCloud

# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_array [as 别名]
def plotTwiiterWordCloud():
	args = sys.argv
	tracefile = open(args[2], 'r')
	nLines = sum(1 for line in tracefile)
	tracefile.seek(0)

	dictTerms = dict()
	blacklist = STOPWORDS.copy()
	blacklist.add('rt')
	punctuation = set(string.punctuation)
	punctuation.remove('@')
	punctuation.remove('&')
	# punctuation.remove('#')
	for line in tqdm(tracefile, total=nLines):
		try:
			linesplited = line.split(', ')
			tweet = linesplited[6].lower()
			for p in punctuation:
				tweet = tweet.replace(p, '')
			terms = tweet.split(' ')
			for t in terms:
				if (len(t) > 1) and 'http' not in t and (t not in blacklist):
					try:
						dictTerms[t] += 1
					except KeyError:
						dictTerms[t] = 1
		except IndexError:
			print 'IndexError'
	for t in blacklist:
		try:
			del dictTerms[t]
		except KeyError:
			continue
	popularTerms = sorted(dictTerms.keys(), key=lambda w:dictTerms[w], reverse=True)
	popularTerms = [p for p in popularTerms if (dictTerms[p]) > 1]
	print len(popularTerms)
	text = list()
	terms = ''
	for p in popularTerms:
		text.append((p, dictTerms[p]))
		for i in range(dictTerms[p]):
			terms += ' ' + p
	# print terms
	maskfile = 'csgo-icon'
	mask = imread(maskfile + '.jpg') # mask=mask
	wc = WordCloud(mask=mask, background_color='white', width=1280, height=720).generate(terms) # max_words=10000
	default_colors = wc.to_array()
	plt.figure()
	plt.imshow(default_colors)
	plt.axis('off')
	plt.savefig(maskfile + '-wordcloud.png', dpi=500, bbox_inches='tight', pad_inches=0) # bbox_inches='tight'
	plt.show()
开发者ID:leokassio,项目名称:csgo-analysis,代码行数:54,代码来源:csgo-analysis.py

示例4: test_default

# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_array [as 别名]
def test_default():
    # test that default word cloud creation and conversions work
    wc = WordCloud(max_words=50)
    wc.generate(THIS)

    # check_list for proper word extraction
    assert_equal(len(wc.words_), wc.max_words)

    # check_list that we got enough words
    assert_equal(len(wc.layout_), wc.max_words)

    # check_list image export
    wc_image = wc.to_image()
    assert_equal(wc_image.size, (wc.width, wc.height))

    # check_list that numpy conversion works
    wc_array = np.array(wc)
    assert_array_equal(wc_array, wc.to_array())

    # check_list size
    assert_equal(wc_array.shape, (wc.height, wc.width, 3))
开发者ID:pipilove,项目名称:TopicModel,代码行数:23,代码来源:test_wordcloud.py

示例5: open

# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_array [as 别名]
# taken from
# http://www.stencilry.org/stencils/movies/star%20wars/storm-trooper.gif
mask = np.array(Image.open(path.join(d, "stormtrooper_mask.png")))

# movie script of "a new hope"
# http://www.imsdb.com/scripts/Star-Wars-A-New-Hope.html
# May the lawyers deem this fair use.
text = open("a_new_hope.txt").read()

# preprocessing the text a little bit
text = text.replace("HAN", "Han")
text = text.replace("LUKE'S", "Luke")

# adding movie script specific stopwords
stopwords = STOPWORDS.copy()
stopwords.add("int")
stopwords.add("ext")

wc = WordCloud(max_words=1000, mask=mask, stopwords=stopwords, margin=10,
               random_state=1).generate(text)
# store default colored image
default_colors = wc.to_array()
plt.title("Custom colors")
plt.imshow(wc.recolor(color_func=grey_color_func, random_state=3))
wc.to_file("a_new_hope.png")
plt.axis("off")
plt.figure()
plt.title("Default colors")
plt.imshow(default_colors)
plt.axis("off")
plt.show()
开发者ID:bommysk,项目名称:Data301FinalProject,代码行数:33,代码来源:wordcloud.py

示例6: pos_tag

# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_array [as 别名]
swords=stopwords.words()
all_words=[i for i in f1 if i.isalpha()]    
all_words=[i for i in all_words if i not in swords]  
all_nouns=[w for w,t in pos_tag(all_words) if t in ['NN','NNS','NNP','NNPS','JJ','JJR','JJS']]
final_set=' '.join(all_nouns)



########################################################
# for testing

text=''
text = open("ahope.txt").read()

########################################################


cloud = WordCloud(max_words=20000, mask=mask, margin=0.1,
               background_color=background_color,
               random_state=2).generate(text)

# store default colored image
default_colors = cloud.to_array()

#plt.figure()
#plt.show()
plt.title("Data Cloud")
plt.imshow(default_colors)
plt.axis("off")
plt.savefig('C:\\Users\\Arslan Qadri\\Google Drive\\Programs\\Python\\temp_codes\\2.jpg',dpi=4000) 
#plt.show()
开发者ID:arslanoqads,项目名称:PyMe,代码行数:33,代码来源:cloud_image_mask.py

示例7: make_wordle_from_mallet

# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_array [as 别名]
def make_wordle_from_mallet(word_weights_file,topics,words,outfolder, font_path, dpi):
    """Generate wordles from Mallet output, using the wordcloud module."""
    print("\nLaunched make_wordle_from_mallet.")
    
    import os
    import pandas as pd
    import random
    import matplotlib.pyplot as plt
    from wordcloud import WordCloud

    if not os.path.exists(outfolder):
        os.makedirs(outfolder)
    
    def read_mallet_output(word_weights_file):
        """Reads Mallet output (topics with words and word weights) into dataframe.""" 
        word_scores = pd.read_table(word_weights_file, header=None, sep="\t")
        word_scores = word_scores.sort(columns=[0,2], axis=0, ascending=[True, False])
        word_scores_grouped = word_scores.groupby(0)
        #print(word_scores.head())
        return word_scores_grouped

    def get_wordlewords(words,topic):
        """Transform Mallet output for wordle generation."""
        topic_word_scores = read_mallet_output(word_weights_file).get_group(topic)
        top_topic_word_scores = topic_word_scores.iloc[0:words]
        topic_words = top_topic_word_scores.loc[:,1].tolist()
        word_scores = top_topic_word_scores.loc[:,2].tolist()
        wordlewords = ""
        j = 0
        for word in topic_words:
            word = word
            score = word_scores[j]
            j += 1
            wordlewords = wordlewords + ((word + " ") * score)
        return wordlewords
        
    def get_color_scale(word, font_size, position, orientation, random_state=None):
        """ Create color scheme for wordle."""
        #return "hsl(0, 00%, %d%%)" % random.randint(80, 100) # Greys for black background.
        return "hsl(221, 65%%, %d%%)" % random.randint(30, 35) # Dark blue for white background

    ## Creates the wordle visualisation, using results from the above functions.
    for topic in range(0,topics):
        ## Defines filename and title for the wordle image.
        figure_filename = "wordle_tp"+"{:03d}".format(topic) + ".png"
        figure_title = "topic "+ "{:02d}".format(topic)        
        ## Gets the text for one topic.
        text = get_wordlewords(words,topic)
        #print(text)
        ## Generates, recolors and saves the wordcloud.
        #original# wordcloud = WordCloud(background_color="white", margin=5).generate(text)
        #font_path = "/home/christof/.fonts/AveriaSans-Regular.ttf"
        wordcloud = WordCloud(font_path=font_path, background_color="white", margin=5).generate(text)
        default_colors = wordcloud.to_array()
        plt.imshow(wordcloud.recolor(color_func=get_color_scale, random_state=3))
        plt.imshow(default_colors)
        plt.imshow(wordcloud)
        plt.title(figure_title, fontsize=24)
        plt.axis("off")
        plt.savefig(outfolder + figure_filename, dpi=dpi)
        plt.close()
    print("Done.")
开发者ID:daschloer,项目名称:tmw,代码行数:64,代码来源:tmw.py

示例8: grey_color_func

# 需要导入模块: from wordcloud import WordCloud [as 别名]
# 或者: from wordcloud.WordCloud import to_array [as 别名]
"""
Minimal Example
===============

"""

from os import path
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import csv
import random

def grey_color_func(word, font_size, position, orientation, random_state=None, **kwargs):
    return "hsl(0, 0%%, %d%%)" % random.randint(60, 100)

d = path.dirname(__file__)

# Read the whole text.
text = open(path.join(d, 'words.txt')).read()

# Generate a word cloud image
wordcloud = WordCloud(stopwords = "im", max_words=2000, width=1600, height=800).generate(text)

default_colors = wordcloud.to_array()
# Open a plot of the generated image.
# plt.imshow(wordcloud)
plt.imshow(wordcloud.recolor(color_func=grey_color_func, random_state=2))
plt.axis("off")
# plt.tight_layout(pad=0)
plt.show()
开发者ID:ApurvaNaik,项目名称:textMiningReddit,代码行数:32,代码来源:myWordCloudBW.py


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