當前位置: 首頁>>代碼示例>>Python>>正文


Python wordcloud.ImageColorGenerator方法代碼示例

本文整理匯總了Python中wordcloud.ImageColorGenerator方法的典型用法代碼示例。如果您正苦於以下問題:Python wordcloud.ImageColorGenerator方法的具體用法?Python wordcloud.ImageColorGenerator怎麽用?Python wordcloud.ImageColorGenerator使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在wordcloud的用法示例。


在下文中一共展示了wordcloud.ImageColorGenerator方法的11個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: draw_word_cloud

# 需要導入模塊: import wordcloud [as 別名]
# 或者: from wordcloud import ImageColorGenerator [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() 
開發者ID:keejo125,項目名稱:web_scraping_and_data_analysis,代碼行數:23,代碼來源:analysis.py

示例2: main

# 需要導入模塊: import wordcloud [as 別名]
# 或者: from wordcloud import ImageColorGenerator [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') 
開發者ID:ljw9609,項目名稱:SentimentAnalysis,代碼行數:24,代碼來源:seg.py

示例3: draw_word_cloud

# 需要導入模塊: import wordcloud [as 別名]
# 或者: from wordcloud import ImageColorGenerator [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() 
開發者ID:keejo125,項目名稱:web_scraping_and_data_analysis,代碼行數:23,代碼來源:news_hot.py

示例4: WordCloudAPI

# 需要導入模塊: import wordcloud [as 別名]
# 或者: from wordcloud import ImageColorGenerator [as 別名]
def WordCloudAPI(request):
        # ImgInfo.objects.filter(UserInfo_id=text).update(wordcloud=res)
        # print("更新完畢~~")
        # wordlist_after_jieba = jieba.cut(content, cut_all=False)
        # wl_space_split = " ".join(wordlist_after_jieba)
        # backgroud_Image = plt.imread(path.dirname(__file__) + '\color.png')
        # '''設置詞雲樣式'''
        # stopwords = STOPWORDS.copy()
        # stopwords.add("哈哈") #可以加多個屏蔽詞
        # wc = WordCloud(
        #     width=770,
        #     height=1200,
        #     background_color='white',# 設置背景顏色
        #     # mask=backgroud_Image,# 設置背景圖片
        #     font_path=path.dirname(__file__) + '\simkai.ttf',  # 設置中文字體,若是有中文的話,這句代碼必須添加,不然會出現方框,不出現漢字
        #     max_words=600, # 設置最大現實的字數
        #     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)#字體顏色為背景圖片的顏色
        # d = path.dirname(__file__)
        # wc.to_file(path.join(d, "wc.jpg"))
        # print('生成詞雲成功!')
        # with open(path.dirname(__file__) + '\wc.jpg', 'rb') as f:
        #     base64_data = base64.b64encode(f.read())
        #     url = base64_data.decode()
        pass 
開發者ID:Superbsco,項目名稱:weibo-analysis-system,代碼行數:32,代碼來源:tests.py

示例5: gen_gradient_mask

# 需要導入模塊: import wordcloud [as 別名]
# 或者: from wordcloud import ImageColorGenerator [as 別名]
def gen_gradient_mask(
    size: int,
    palette: str,
    icon_dir: str = ".temp",
    gradient_dir: str = "horizontal",
    invert_mask: bool = False,
):
    """Generates a gradient color mask from a specified palette."""
    mask_array = gen_mask_array(icon_dir, invert_mask, size)
    mask_array = np.float32(mask_array)

    palette_func = gen_palette(palette)
    gradient = np.array(makeMappingArray(size, palette_func.mpl_colormap))

    # matplotlib color maps are from range of (0, 1). Convert to RGB.
    gradient *= 255.0

    # Add new axis and repeat gradient across it.
    gradient = np.tile(gradient, (size, 1, 1))

    # if vertical, transpose the gradient.
    if gradient_dir == "vertical":
        gradient = np.transpose(gradient, (1, 0, 2))

    # Turn any nonwhite pixels on the icon into the gradient colors.
    white = (255.0, 255.0, 255.0, 255.0)
    mask_array[mask_array != white] = gradient[mask_array != white]

    image_colors = ImageColorGenerator(mask_array)
    return image_colors, np.uint8(mask_array) 
開發者ID:minimaxir,項目名稱:stylecloud,代碼行數:32,代碼來源:stylecloud.py

示例6: drawWordCloud

# 需要導入模塊: import wordcloud [as 別名]
# 或者: from wordcloud import ImageColorGenerator [as 別名]
def drawWordCloud(self, word_text, filename, dict_type=False, background_image='image/tom2.jpeg'):
        """

        :param word_text:
        :param filename:
        :param dict_type:
        :param background_image: 詞雲圖的背景形狀
        :return:
        """
        mask = Image.open(BASE_DIR + background_image)
        mask = np.array(mask)
        my_wordcloud = WordCloud(
            background_color='white',  # 設置背景顏色
            mask=mask,  # 設置背景圖片
            max_words=2000,  # 設置最大現實的字數
            stopwords=STOPWORDS,  # 設置停用詞
            font_path=self.system_font,  # 設置字體格式,如不設置顯示不了中文
            max_font_size=50,  # 設置字體最大值
            random_state=30,  # 設置有多少種隨機生成狀態,即有多少種配色方案
            scale=1.3
        )
        if not dict_type:
            my_wordcloud = my_wordcloud.generate(word_text)
        else:
            my_wordcloud = my_wordcloud.fit_words(word_text)
        image_colors = ImageColorGenerator(mask)
        my_wordcloud.recolor(color_func=image_colors)
        # 以下代碼顯示圖片
        plt.imshow(my_wordcloud)
        plt.axis("off")
        # 保存圖片
        if not self.from_web:
            my_wordcloud.to_file(filename=self.image_path + filename + '.jpg')
            print("result file path:", self.image_path + filename + '.jpg')
            plt.show()
        else:
            my_wordcloud.to_file(filename=self.web_image_bash_path + filename + '.jpg')
            print("result file path:", self.web_image_bash_path + filename + '.jpg') 
開發者ID:Maicius,項目名稱:QQZoneMood,代碼行數:40,代碼來源:QQZoneAnalysis.py

示例7: show

# 需要導入模塊: import wordcloud [as 別名]
# 或者: from wordcloud import ImageColorGenerator [as 別名]
def show(file, pic):
    global main_dir
    d = path.dirname(__file__)
    text = open(path.join(d, main_dir+file), encoding='utf-8').read()
    # 自定義圖片
    my_coloring = np.array(Image.open(path.join(d, pic)))

    # 設置停用詞
    stopwords = set(STOPWORDS)
    stopwords.add("")

    # 設置詞雲形狀
    wc = WordCloud(font_path='simhei.ttf', width=800, height= 600, background_color="white", max_words=300, mask=my_coloring,
                   stopwords=stopwords, max_font_size=110, random_state=200)
    # 運行統計
    wc.generate(text)

    # 獲取color
    image_colors = ImageColorGenerator(my_coloring)

    # 展示
    plt.imshow(wc, interpolation="bilinear")
    plt.axis("off")
    plt.figure()
    wc.to_file(file+'_1.png')

    # 按照給定的圖片顏色布局生成字體顏色
    plt.imshow(wc.recolor(color_func=image_colors), interpolation="bilinear")
    plt.axis("off")
    plt.figure()
    wc.to_file(file+'_2.png')

    plt.imshow(my_coloring, cmap=plt.cm.gray, interpolation="bilinear")
    plt.axis("off")
    plt.show() 
開發者ID:ZubinGou,項目名稱:AI_Poet_Totoro,代碼行數:37,代碼來源:歌詞_6詞雲.py

示例8: make_wc_custom

# 需要導入模塊: import wordcloud [as 別名]
# 或者: from wordcloud import ImageColorGenerator [as 別名]
def make_wc_custom(self, mask, text, max):
		try:
			coloring = np.array(PIL.Image.open(mask))
			wc = WordCloud(width=1024, height=768, max_words=max, mask=coloring)
			wc = wc.generate(' '.join(text))
			image_colors = ImageColorGenerator(coloring)
			wc = wc.recolor(color_func=image_colors)
			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,代碼行數:16,代碼來源:Wc.py

示例9: wordCloud

# 需要導入模塊: import wordcloud [as 別名]
# 或者: from wordcloud import ImageColorGenerator [as 別名]
def wordCloud(wordList):
    from wordcloud import WordCloud, ImageColorGenerator
    import matplotlib.pyplot as plt
    import numpy as np
    import PIL.Image as Image
    import os
    d = os.path.dirname(__file__)
    img = Image.open(os.path.join(d, "jupiter.png"))
    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, "../font/PingFang.ttc")))
    my_wordcloud = my_wordcloud.generate_from_frequencies(wordList)

    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("jupiter_wordcloud_1.png")
    plt.show() 
開發者ID:keejo125,項目名稱:web_scraping_and_data_analysis,代碼行數:28,代碼來源:generate_wordcloud.py

示例10: main

# 需要導入模塊: import wordcloud [as 別名]
# 或者: from wordcloud import ImageColorGenerator [as 別名]
def main(input_filename):
    content = '\n'.join([line.strip()
                        for line in codecs.open(input_filename, 'r', 'utf-8')
                        if len(line.strip()) > 0])
    stopwords = set([line.strip()
                    for line in codecs.open(stopwords_filename, 'r', 'utf-8')])

    segs = jieba.cut(content)
    words = []
    for seg in segs:
        word = seg.strip().lower()
        if len(word) > 1 and word not in stopwords:
            words.append(word)

    words_df = pandas.DataFrame({'word':words})
    words_stat = words_df.groupby(by=['word'])['word'].agg({'number' : np.size})
    words_stat = words_stat.reset_index().sort_values(by="number",ascending=False)

    print '# of different words =', len(words_stat)

    input_prefix = input_filename
    if input_filename.find('.') != -1:
        input_prefix = '.'.join(input_filename.split('.')[:-1])

    for file in listdir(template_dir):
        if file[-4:] != '.png' and file[-4:] != '.jpg':
            continue
        background_picture_filename = join(template_dir, file)
        if isfile(background_picture_filename):
            prefix = file.split('.')[0]
            
            bimg=imread(background_picture_filename)
            wordcloud=WordCloud(font_path=font_filename,background_color='white',mask = bimg,max_font_size=600,random_state=100)
            wordcloud=wordcloud.fit_words(dict(words_stat.head(4000).itertuples(index=False)))

            bimgColors=ImageColorGenerator(bimg)
            wordcloud.recolor(color_func=bimgColors)

            output_filename = prefix + '_' + input_prefix + '.png'

            print 'Saving', output_filename
            wordcloud.to_file(output_filename) 
開發者ID:shangjingbo1226,項目名稱:ChineseWordCloud,代碼行數:44,代碼來源:create_word_cloud.py

示例11: main

# 需要導入模塊: import wordcloud [as 別名]
# 或者: from wordcloud import ImageColorGenerator [as 別名]
def main():
    doc = '''傑森我愛你!加油你是最棒的!'''
    start_time = time.time()
    datalist = Seg().get_data_from_mysql(5, 0)
    npl = SimpleNLP(1, doc, datalist)
    print(npl.seg_doc())
    print(npl.seg_datalist())

    keyword = npl.get_keyword_datalist()
    print(keyword)
    print(len(keyword))
    '''
    font_path = root_path+'/data/simfang.ttf'
    bg_path = root_path + '/data/bg.jpg'
    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, width=1000, height=800, margin=2, random_state=48)
    wordcloud.generate_from_frequencies(keyword)
    plt.figure()
    plt.imshow(wordcloud.recolor(color_func=image_colors))
    plt.axis("off")
    plt.show()
    wordcloud.to_file(root_path + '/data/pic2.png')
    
    print(npl.sentiment_analysis_doc())
    res = npl.sentiment_analysis_datalist()
    # max_qty = Counter(res).most_common(1)[0][1]
    # print(max_qty)
    print(res)
    res2 = np.array(res)
    mean = np.mean(res2)
    print(mean)

    # plt.hist(res2, bins=np.arange(0, 1, 0.005))
    # plt.title("sentiment")
    # plt.xlabel("score")
    # plt.ylabel("amount")
    # plt.show()

    end_time = time.time()
    print(end_time - start_time)

    # f = open(root_path + '/data/10w-nb-30000v2', 'w')
    # f.write(str(res))
    # f.close()
    ''' 
開發者ID:ljw9609,項目名稱:SentimentAnalysis,代碼行數:49,代碼來源:__init__.py


注:本文中的wordcloud.ImageColorGenerator方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。