《数据分析实战 45 讲》 学习笔记 Day 24

173 阅读3分钟

38丨数据可视化实战:如何给毛不易的歌曲做词云展示?

那么在今天的实战项目里,有 3 个目标需要掌握:掌握词云分析工具,并进行可视化呈现;掌握 Python 爬虫,对网页的数据进行爬取;掌握 XPath 工具,分析提取想要的元素 。
如何制作词云

wc = WordCloud(
    background_color='white',# 设置背景颜色
    mask=backgroud_Image,# 设置背景图片
    font_path='./SimHei.ttf',  # 设置字体,针对中文的情况需要设置中文字体,否则显示乱码
    max_words=100, # 设置最大的字数
    stopwords=STOPWORDS,# 设置停用词
  max_font_size=150,# 设置字体最大值
  width=2000,# 设置画布的宽度
  height=1200,# 设置画布的高度
    random_state=30# 设置多少种随机状态,即多少种颜色
)

给毛不易的歌词制作词云

假设我们现在要给毛不易的歌词做个词云,那么需要怎么做呢?我们先把整个项目的流程梳理下:

image.png
在准备阶段:我们主要使用 Python 爬虫获取 HTML,用 XPath 对歌曲的 ID、名称进行解析,然后通过网易云音乐的 API 接口获取每首歌的歌词,最后将所有的歌词合并得到一个变量。在词云分析阶段,我们需要创建 WordCloud 词云类,分析得到的歌词文本,最后可视化。基于上面的流程,编写代码如下:

# -*- coding:utf-8 -*-
# 网易云音乐 通过歌手ID,生成该歌手的词云
import requests
import sys
import re
import os
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import jieba
from PIL import Image
import numpy as np
from lxml import etree
 
headers = {
       'Referer'  :'http://music.163.com',
       'Host'     :'music.163.com',
       'Accept'   :'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
       'User-Agent':'Chrome/10'
    }
 
# 得到某一首歌的歌词
def get_song_lyric(headers,lyric_url):
    res = requests.request('GET', lyric_url, headers=headers)
    if 'lrc' in res.json():
       lyric = res.json()['lrc']['lyric']
       new_lyric = re.sub(r'[\d:.[\]]','',lyric)
       return new_lyric
    else:
       return ''
       print(res.json())
# 去掉停用词
def remove_stop_words(f):
    stop_words = ['作词', '作曲', '编曲', 'Arranger', '录音', '混音', '人声', 'Vocal', '弦乐', 'Keyboard', '键盘', '编辑', '助理', 'Assistants', 'Mixing', 'Editing', 'Recording', '音乐', '制作', 'Producer', '发行', 'produced', 'and', 'distributed']
    for stop_word in stop_words:
       f = f.replace(stop_word, '')
    return f
# 生成词云
def create_word_cloud(f):
    print('根据词频,开始生成词云!')
    f = remove_stop_words(f)
    cut_text = " ".join(jieba.cut(f,cut_all=False, HMM=True))
    wc = WordCloud(
       font_path="./wc.ttf",
       max_words=100,
       width=2000,
       height=1200,
    )
    print(cut_text)
    wordcloud = wc.generate(cut_text)
    # 写词云图片
    wordcloud.to_file("wordcloud.jpg")
    # 显示词云文件
    plt.imshow(wordcloud)
    plt.axis("off")
    plt.show()
# 得到指定歌手页面 热门前50的歌曲ID,歌曲名
def get_songs(artist_id):
    page_url = 'https://music.163.com/artist?id=' + artist_id
    # 获取网页HTML
    res = requests.request('GET', page_url, headers=headers)
    # 用XPath解析 前50首热门歌曲
    html = etree.HTML(res.text)
    href_xpath = "//*[@id='hotsong-list']//a/@href"
    name_xpath = "//*[@id='hotsong-list']//a/text()"
    hrefs = html.xpath(href_xpath)
    names = html.xpath(name_xpath)
    # 设置热门歌曲的ID,歌曲名称
    song_ids = []
    song_names = []
    for href, name in zip(hrefs, names):
       song_ids.append(href[9:])
       song_names.append(name)
       print(href, '  ', name)
    return song_ids, song_names
# 设置歌手ID,毛不易为12138269
artist_id = '12138269'
[song_ids, song_names] = get_songs(artist_id)
# 所有歌词
all_word = ''
# 获取每首歌歌词
for (song_id, song_name) in zip(song_ids, song_names):
    # 歌词API URL
    lyric_url = 'http://music.163.com/api/song/lyric?os=pc&id=' + song_id + '&lv=-1&kv=-1&tv=-1'
    lyric = get_song_lyric(headers, lyric_url)
    all_word = all_word + ' ' + lyric
    print(song_name)
#根据词频 生成词云
create_word_cloud(all_word)

总结今天我给你讲了词云的可视化。在这个实战中,你能看到前期的数据准备在整个过程中占了很大一部分。如果你用 Python 作为数据采集工具,就需要掌握 Python 爬虫和 XPath 解析,掌握这两个工具最好的方式就是多做练习。我们今天讲到了词云工具 WordCloud,它是一个很好用的 Python 工具,可以将复杂的文本通过词云图的方式呈现。需要注意的是,当我们需要使用中文字体的时候,比如黑体 SimHei,就可以将 WordCloud 中的 font_path 属性设置为 SimHei.ttf,你也可以设置其他艺术字体,在给毛不易的歌词做词云展示的时候,我们就用到了艺术字体。你可以从 GitHub 上下载字体和代码:github.com/cystanford/…

image.png最后给你留一道思考题吧。我抓取了毛不易主页的歌词,是以歌手主页为粒度进行的词云可视化。实际上网易云音乐也有歌单的 API,比如music.163.com/api/playlis… ID 为 753776811)呢?