其他
用Python分析了波周杰伦,还做了数据可视化
首先,需要引入 JSON 库(未安装者通过 pip install json 安装)。
import json
然后,读取我们下载的 JSON 文件,存储在名为 data 的变量中。
with open(‘ lyrics.json’ , ‘ r’ ) as f:
data = json.load(f)
接着,遍历 data 中的每一项,找出“歌手”=“周杰伦”的数据项,存到data_zjl 中。
data_zjl = [item for item in data if item[‘ singer’ ]==’ 周杰伦’ ]
print(len(data_zjl))
建立一个空列表 zjl_lyrics,用于存储歌词。遍历 data_zjl 中的每一首歌,将它们的歌词存到 zjl_lyrics 中。
Zjl_lyrics = []
for song in data_zjl:
zjl_lyrics = zjl_lyrics + song[‘ lyric’ ]
最后将 zjl_lyrics 写入一个新的 .txt 文件。
with open(“ zjl_lyrics.txt” , “ w” ) as outfifile:
outfifile.write(“ \n” .join(zjl_lyrics))
图1
以下附上一种在 Python 中分词的方法。首先引入 jieba 库(安装 :pip install jieba)、pandas 库(安装 :pip install pandas)、用于频次统计的 Counter 库,以及表单工具,代码如下。
import jieba
import jieba.analyse
import pandas as pd
from collections import Counter
with open(‘ chinese_stop_words.txt’ ) as f:
stopwords = [line.strip() for line in f.readlines()]
打开歌词文件,利用 jieba 库进行分词。分词之后,删除停用词、去除无用的符号等。用 Counter 库对清洗干净的词语进行频次统计。然后将统计结果用 pandas库转换为数据表单,存储为 Excel 文件,代码如下。
fifile = open(“ zjl_lyrics.txt” ).read()
words = jieba.lcut(fifile, cut_all=False, use_paddle=True)
words = [w for w in words if w not in stopwords]
words = [w.strip() for w in words]
words = [w for w in words if w != ‘ ’ ]
words_fifilter = [w for w in words if len(w) > 1]
df = pd.DataFrame.from_dict(Counter(words_fifilter), orient=’ index’ ).
reset_index()
df = df.rename(columns={‘ index’ :’ words’ , 0:’ count’ })
df.to_excel(“ 周杰伦分词结果 .xlsx” )
表1
由于是文本类数据,我们首先想到的可视化形式可能是文字云。如果你使用 Python,则可以直接基于刚才的分析结果,调用wordcloud库绘制文字云,代码如下。
from wordcloud import WordCloud
# 注 :这里需要引入一个中文字体,否则会乱码
wc = WordCloud(font_path = ‘ Alibaba-PuHuiTi-Regular.ttf’ ,
background_color=” white” ,
max_words = 2000)
wc.generate(‘ ‘ .join(words_fifilter))
import matplotlib.pyplot as plt
plt.imshow(wc)
plt.fifigure(fifigsize=(12,10), dpi = 300)
plt.axis(“ off” )
plt.show()
图2
图3
图5
本文节选自《数据可视化设计指南:从数据到新知(全彩)》一书。