分析爬取的網(wǎng)易云音樂(lè)歌詞生成詞云

上篇文章我們成功獲取到了 等什么君 的歌詞,那么我們就分析下,她都寫(xiě)了些什么。

1.生成一個(gè)歌詞文件

使用上篇文章寫(xiě)的write_fil_txt方法把歌詞寫(xiě)入一個(gè)文件中

def write_fil_txt(singer_name, lyric):
    print('正在寫(xiě)入{}歌曲...'.format(singer_name))
    if lyric is not None:
        with open('{}.txt'.format(singer_name), 'a', encoding='utf-8') as fp:
            fp.write(lyric)

生成的一個(gè)名為 等什么君.txt 的歌詞文件


2.讀取停用詞

def stop_words_list(filepath):
    stop_words = [file_line.strip() for file_line in open(filepath, 'r', encoding='utf-8').readlines()]
    return stop_words

3.對(duì)歌詞分詞

使用jieba分詞庫(kù)對(duì)爬下來(lái)的歌詞進(jìn)行分詞

def seg_sentence(sentence):
    sentence_seg = jieba.cut(sentence.strip())
    stop_words = stop_words_list('停用詞表.txt')  # 這里加載停用詞路徑
    stop_words.append("版權(quán)") # 這里可以自定義停用詞
    stop_words.append("授權(quán)")
    out_str = ''
    for word in sentence_seg:
        if word not in stop_words:
            if word != '\t':
                out_str += word
                out_str += " "
    return out_str

4.生成詞云

def create_word_cloud():
    curr_path = os.path.dirname(__file__)  # 當(dāng)前文件文件夾所在的目錄
    font_path = os.path.join(curr_path, 'AaDouBanErTi-2.ttf')
    inputs = open('等什么君.txt', 'r', encoding='utf-8')
    outputs = open('等什么君-分詞.txt', 'w', encoding='gbk')
    for line in inputs:
        line_seg = seg_sentence(line)  # 這里返回的是字符串
        outputs.write(line_seg + '\n')
    inputs.close()
    outputs.close()
    cloud = WordCloud(font_path=font_path)
    cut_texts = open('等什么君-分詞.txt', 'r', encoding='gbk').read()
    word_cloud = cloud.generate(cut_texts)  # 生成詞云
    word_cloud.to_file('word_cloud.png')  # 保存圖片
    image = word_cloud.to_image()  # 轉(zhuǎn)化為圖片
    image.show()  # 展示圖片

獲取當(dāng)前的目錄留用
同時(shí)中文必須要指定中文字體才行,順便推薦一個(gè)免費(fèi)的字體網(wǎng)站:字體天下
調(diào)用seg_sentence方法進(jìn)行分詞處理
再調(diào)用WordCloud方法生成詞云圖片,官方文檔地址:wordcloud文檔

5.生成的詞云圖


執(zhí)行完以后生成的詞云圖便是如上圖,但是不得不說(shuō)是真的丑呀,所以我又參考了下官方文檔優(yōu)化下。

6.根據(jù)圖片顏色摳圖

這里利用剛剛生成的 等什么君-分詞.txt 文件進(jìn)行詞云生成,根據(jù)提供的背景圖片適配所處位置文字的顏色。

def image_colors():
    d = os.path.dirname(__file__) if "__file__" in locals() else os.getcwd()
    text = open(os.path.join(d, '等什么君-分詞.txt')).read()

    image_color = np.array(Image.open(os.path.join(d, 'gufeng.png')))
    image_color = image_color[::3, ::3]

    image_mask = image_color.copy()
    image_mask[image_mask.sum(axis=2) == 0] = 255

    edges = np.mean([gaussian_gradient_magnitude(image_color[:, :, i] / 255., 2) for i in range(3)], axis=0)
    image_mask[edges > .08] = 255

    wc = WordCloud(font_path='AaDouBanErTi-2.ttf',
                   max_words=2000, mask=image_mask, max_font_size=40, random_state=42, relative_scaling=0)
    wc.generate(text)
    # plt.imshow(wc)  # 詞云的普通顏色

    image_color_generator = ImageColorGenerator(image_color)
    wc.recolor(color_func=image_color_generator)
    plt.figure(figsize=(10, 10))
    plt.imshow(wc, interpolation="bilinear")
    wc.to_file("等什么君-詞云.png")
    plt.show()

7.優(yōu)化后的詞云圖片

運(yùn)行上面的代碼生成的詞云圖片如下:



哈哈,是不是漂亮了很多,這才有詞云的樣子嘛。

8.使用第三方詞云生成網(wǎng)站

要使用第三方詞云網(wǎng)站,那么需要再把分詞后的數(shù)據(jù)優(yōu)化下,坐下統(tǒng)計(jì)生成權(quán)值,也就是出現(xiàn)的次數(shù),并且把結(jié)果輸出到xls文件中,實(shí)現(xiàn)代碼如下:

def analyse_export():
    wbk = xlwt.Workbook(encoding='ascii')
    sheet = wbk.add_sheet("WordCount")  # Excel單元格名字
    word_list = []
    key_list = []
    for line in open('等什么君-分詞.txt', encoding='gbk'):
        item = line.strip('\n\r').split('\t')  # 制表格切分
        tags = analyse.extract_tags(item[0])  # jieba分詞分析
        for t in tags:
            word_list.append(t)
    word_dict = {}
    with open('等什么君-分析.txt', 'w') as wf2:
        for term in word_list:
            if term not in word_dict:
                word_dict[term] = 1
            else:
                word_dict[term] += 1
        order_list = list(word_dict.values())
        order_list.sort(reverse=True)
        # print(order_list)
        for i in range(len(order_list)):
            for key in word_dict:
                if word_dict[key] == order_list[i]:
                    wf2.write(key + ' ' + str(word_dict[key]) + '\n')  # 寫(xiě)入txt文檔
                    key_list.append(key)
                    word_dict[key] = 0

    for i in range(len(key_list)):
        sheet.write(i, 1, label=order_list[i])
        sheet.write(i, 0, label=key_list[i])
    wbk.save('等什么君-分析.xls')  # 保存為xls文件

結(jié)果如下:


第三方網(wǎng)站有很多:wordleworditout
tagxedowordarttocloud圖悅BDP個(gè)人版等等。
我這使用的是wordart:
WORDS -> Import -> 把xls中內(nèi)容拷貝到這里 -> Import words


SHAPES -> Add image -> Open image from your computer選擇要上傳的圖片->OK

FONTS -> Add font -> 選擇字體 ->打開(kāi)

最后點(diǎn)擊 Visualize 即可:

很明顯,有了權(quán)值之后生成的詞云圖片更好看,不過(guò)這個(gè)網(wǎng)站下載高清圖片是需要收費(fèi)的,普通的下載不收費(fèi)。
好了,通過(guò)這個(gè)詞云圖能清晰的看出 君大 都寫(xiě)了些什么。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。