当前位置: 首页>>代码示例>>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;未经允许,请勿转载。