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


Python wordcloud.WordCloud方法代碼示例

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


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

示例1: generate_wordcloud

# 需要導入模塊: import wordcloud [as 別名]
# 或者: from wordcloud import WordCloud [as 別名]
def generate_wordcloud(df, save_cfg=cfg.saving_config):
    brain_mask = np.array(Image.open("./img/brain_stencil.png"))

    def transform_format(val):
        if val == 0:
            return 255
        else:
            return val

    text = (df['Title']).to_string()

    stopwords = set(STOPWORDS)
    stopwords.add("using")
    stopwords.add("based")

    wc = WordCloud(
        background_color="white", max_words=2000, max_font_size=50, mask=brain_mask,
        stopwords=stopwords, contour_width=1, contour_color='steelblue')
    wc.generate(text)

    # store to file
    if save_cfg is not None:
        fname = os.path.join(save_cfg['savepath'], 'DL-EEG_WordCloud')
        wc.to_file(fname + '.' + save_cfg['format']) #, **save_cfg) 
開發者ID:hubertjb,項目名稱:dl-eeg-review,代碼行數:26,代碼來源:analysis.py

示例2: test_write_wordclouds_to_folder

# 需要導入模塊: import wordcloud [as 別名]
# 或者: from wordcloud import WordCloud [as 別名]
def test_write_wordclouds_to_folder(tmpdir):
    try:
        import lda
        import PIL
        from wordcloud import WordCloud
    except ImportError:
        pytest.skip('at least one of lda, Pillow, wordcloud not installed')

    path = tmpdir.mkdir('wordclouds').dirname

    data = model_io.load_ldamodel_from_pickle('tests/data/tiny_model_reuters_5_topics.pickle')
    model = data['model']
    vocab = data['vocab']

    phi = model.topic_word_
    assert phi.shape == (5, len(vocab))

    topic_word_clouds = visualize.generate_wordclouds_for_topic_words(phi, vocab, 10)

    visualize.write_wordclouds_to_folder(topic_word_clouds, path, 'cloud_{label}.png')

    for label in topic_word_clouds.keys():
        assert os.path.exists(os.path.join(path, 'cloud_{label}.png'.format(label=label))) 
開發者ID:WZBSocialScienceCenter,項目名稱:tmtoolkit,代碼行數:25,代碼來源:test_topicmod_visualize.py

示例3: generate_wordclouds_for_topic_words

# 需要導入模塊: import wordcloud [as 別名]
# 或者: from wordcloud import WordCloud [as 別名]
def generate_wordclouds_for_topic_words(topic_word_distrib, vocab, top_n, topic_labels='topic_{i1}', which_topics=None,
                                        return_images=True, **wordcloud_kwargs):
    """
    Generate wordclouds for the top `top_n` words of each topic in `topic_word_distrib`.

    :param topic_word_distrib: topic-word distribution; shape KxM, where K is number of topics, M is vocabulary size
    :param vocab: vocabulary array of length M
    :param top_n: number of top values to take from each row of `distrib`
    :param topic_labels: labels used for each row; determine keys in in result dict; either single format string with
                         placeholders ``"{i0}"`` (zero-based topic index) or ``"{i1}"`` (one-based topic index), or
                         list of topic label strings
    :param which_topics: if not None, a sequence of indices into rows of `topic_word_distrib` to select only these
                         topics to generate wordclouds from
    :param return_images: if True, store image objects instead of :class:`wordcloud.WordCloud` objects in the result
                          dict
    :param wordcloud_kwargs: pass additional options to :class:`wordcloud.WordCloud`; updates options in
           :data:`~tmtoolkit.topicmod.visualize.DEFAULT_WORDCLOUD_KWARGS`
    :return: dict mapping row labels to wordcloud images or instances generated from each topic
    """
    return generate_wordclouds_from_distribution(topic_word_distrib, row_labels=topic_labels, val_labels=vocab,
                                                 top_n=top_n, which_rows=which_topics, return_images=return_images,
                                                 **wordcloud_kwargs) 
開發者ID:WZBSocialScienceCenter,項目名稱:tmtoolkit,代碼行數:24,代碼來源:visualize.py

示例4: lyrics

# 需要導入模塊: import wordcloud [as 別名]
# 或者: from wordcloud import WordCloud [as 別名]
def lyrics():
    with open('lyrics.json', 'r', encoding='utf-8') as f:
        data = json.load(f)
    tokens = list()
    for v in data.values():
        # 斷詞後的結果, 若非空白且長度為 2 以上, 則列入詞庫
        tokens += [seg for seg in jieba.cut(v) if seg.split() and len(seg) > 1]

    # 計算 tokens 內各詞彙的出現次數
    counter = Counter(tokens)
    print(counter.most_common(10))

    # 文字雲, 要顯示中文需附上字型檔
    wcloud = WordCloud(font_path='NotoSansMonoCJKtc-Regular.otf').generate(' '.join(tokens))
    plt.imshow(wcloud)
    plt.axis('off')
    plt.show() 
開發者ID:jwlin,項目名稱:web-crawler-tutorial,代碼行數:19,代碼來源:lyric_nlp.py

示例5: run

# 需要導入模塊: import wordcloud [as 別名]
# 或者: from wordcloud import WordCloud [as 別名]
def run(db, args):
    if platform.system() == "Darwin":
        mpl.use("TkAgg")

    import matplotlib.pyplot as plt

    title = "Top reused passwords for {}".format(args.domain)
    passwords = db.all_passwords

    wc = WordCloud(background_color="black", width=1280, height=800, margin=5, max_words=1000, color_func=__get_password_color(passwords))
    wc.generate(" ".join([password for password, score in passwords]))

    plt.title(title)
    plt.imshow(wc, interpolation="nearest", aspect="equal")
    plt.axis("off")
    plt.show() 
開發者ID:eth0izzle,項目名稱:cracke-dit,代碼行數:18,代碼來源:password_cloud.py

示例6: generate_word_cloud

# 需要導入模塊: import wordcloud [as 別名]
# 或者: from wordcloud import WordCloud [as 別名]
def generate_word_cloud():
    """
    生成詞雲
    :return:
    """
    with open(filename, 'r') as f:
        word_content = f.read()

        # 使用jieba去分割
        wordlist = jieba.cut(word_content, cut_all=True)

        wl_space_split = " ".join(wordlist)

        font = r'/Users/xingag/Library/Fonts/SimHei.ttf'

        wordcloud = WordCloud(font_path=font, width=1080, height=1920, margin=2).generate(wl_space_split)

        # 顯示圖片
        plt.imshow(wordcloud)
        plt.axis("off")

        # 按照設置保存到本地文件夾
        wordcloud.to_file("./output.png") 
開發者ID:xingag,項目名稱:spider_python,代碼行數:25,代碼來源:nzj.py

示例7: create_wordcloud

# 需要導入模塊: import wordcloud [as 別名]
# 或者: from wordcloud import WordCloud [as 別名]
def create_wordcloud(content,image='weibo.jpg',max_words=5000,max_font_size=50):

    cut_text = " ".join(content)
    cloud = WordCloud(
        # 設置字體,不指定就會出現亂碼
        font_path="HYQiHei-25J.ttf",
        # 允許最大詞匯
        max_words=max_words,
        # 設置背景色
        # background_color='white',
        # 最大號字體
        max_font_size=max_font_size
    )
    word_cloud = cloud.generate(cut_text)
    word_cloud.to_file(image)

# 分詞並去除停用詞 
開發者ID:starFalll,項目名稱:Spider,代碼行數:19,代碼來源:Data_analysis.py

示例8: gen_img

# 需要導入模塊: import wordcloud [as 別名]
# 或者: from wordcloud import WordCloud [as 別名]
def gen_img(texts, img_file):
    data = ' '.join(text for text in texts)
    image_coloring = imread(img_file)
    wc = WordCloud(
        background_color='white',
        mask=image_coloring,
        font_path='/Library/Fonts/STHeiti Light.ttc'
    )
    wc.generate(data)

    # plt.figure()
    # plt.imshow(wc, interpolation="bilinear")
    # plt.axis("off")
    # plt.show()

    wc.to_file(img_file.split('.')[0] + '_wc.png') 
開發者ID:gaussic,項目名稱:weibo_wordcloud,代碼行數:18,代碼來源:weibo_cloud.py

示例9: show_wordCloud

# 需要導入模塊: import wordcloud [as 別名]
# 或者: from wordcloud import WordCloud [as 別名]
def show_wordCloud(word_freq):
    """
    詞雲顯示
    """
    font = r'C:\Windows\Fonts\msyh.ttc'  # 指定字體,不指定會報錯
    color_mask = imread("resource/timg.jpg")  # 讀取背景圖片
    wcloud = WordCloud(
        font_path=font,
        # 背景顏色
        background_color="white",
        # 詞雲形狀
        mask=color_mask,
        # 允許最大詞匯
        max_words=2000,
        # 最大號字體
        max_font_size=80)

    wcloud.generate_from_frequencies(dict(word_freq))
    # 以下代碼顯示圖片
    plt.imshow(wcloud)
    plt.axis("off")
    plt.show()
    wcloud.to_file("data/wcimage/雪中_1.png") 
開發者ID:jarvisqi,項目名稱:nlp_learning,代碼行數:25,代碼來源:gensim_jb.py

示例10: show_wordCloud

# 需要導入模塊: import wordcloud [as 別名]
# 或者: from wordcloud import WordCloud [as 別名]
def show_wordCloud(word_freq):
    """
    詞雲顯示
    """
    font = r'C:\Windows\Fonts\msyh.ttc'  # 指定字體,不指定會報錯  
    color_mask = imread("resource/timg.jpg")  # 讀取背景圖片
    wcloud = WordCloud(
        font_path=font,
        # 背景顏色
        background_color="white",
        # 詞雲形狀
        mask=color_mask,
        # 允許最大詞匯
        max_words=2000,
        # 最大號字體
        max_font_size=80)

    wcloud.generate_from_frequencies(dict(word_freq))
    # 以下代碼顯示圖片
    plt.imshow(wcloud)
    plt.axis("off")
    plt.show()
    wcloud.to_file("data/wcimage/三體詞雲_3.png") 
開發者ID:jarvisqi,項目名稱:nlp_learning,代碼行數:25,代碼來源:jieba_segment.py

示例11: show_wordCloud

# 需要導入模塊: import wordcloud [as 別名]
# 或者: from wordcloud import WordCloud [as 別名]
def show_wordCloud(word_freq):
    """
    詞雲顯示
    """
    font = r'C:\Windows\Fonts\msyh.ttc'  # 指定字體,不指定會報錯
    color_mask = imread("resource/timg.jpg")  # 讀取背景圖片
    wcloud = WordCloud(
        font_path=font,
        # 背景顏色
        background_color="white",
        # 詞雲形狀
        mask=color_mask,
        # 允許最大詞匯
        max_words=2000,
        # 最大號字體
        max_font_size=80)

    wcloud.generate_from_frequencies(dict(word_freq))
    # 以下代碼顯示圖片
    plt.imshow(wcloud)
    plt.axis("off")
    plt.show()
    wcloud.to_file("data/wcimage/三體詞雲_3.png") 
開發者ID:jarvisqi,項目名稱:nlp_learning,代碼行數:25,代碼來源:pyltp_segment.py

示例12: main

# 需要導入模塊: import wordcloud [as 別名]
# 或者: from wordcloud import WordCloud [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

示例13: PrintWorfCloud

# 需要導入模塊: import wordcloud [as 別名]
# 或者: from wordcloud import WordCloud [as 別名]
def PrintWorfCloud(self,documents,backgroundImgPath,fontPath):
        '''Print out the word cloud of all news(articles/documents).

        # Arguments:
            documents: Overall raw documents.
            backgroundImgPath: Background image path.
            fontPath: The path of windows fonts that used to create the word-cloud.
        '''
        from scipy.misc import imread
        import matplotlib.pyplot as plt
        from wordcloud import WordCloud
        corpora_documents = self.jieba_tokenize(documents) #分詞
        for k in range(len(corpora_documents)):
            corpora_documents[k] = ' '.join(corpora_documents[k])
        corpora_documents = ' '.join(corpora_documents)
        color_mask = imread(backgroundImgPath) #"C:\\Users\\lenovo\\Desktop\\Text_Mining\\3.jpg"
        cloud = WordCloud(font_path=fontPath,mask=color_mask,background_color='white',\
                          max_words=2000,max_font_size=40) #"C:\\Windows\\Fonts\\simhei.ttf"
        word_cloud = cloud.generate(corpora_documents) 
        plt.imshow(word_cloud, interpolation='bilinear')
        plt.axis("off") 
開發者ID:DemonDamon,項目名稱:Listed-company-news-crawl-and-text-analysis,代碼行數:23,代碼來源:text_processing.py

示例14: draw_word_cloud

# 需要導入模塊: import wordcloud [as 別名]
# 或者: from wordcloud import WordCloud [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

示例15: draw_word_cloud

# 需要導入模塊: import wordcloud [as 別名]
# 或者: from wordcloud import WordCloud [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


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