数据集是《数亦有道》第六章6.3节评论数据情感分析的时间序列可视化练习,数据集可从GitHub下载,评价数据集下载
需要调用的模块有SnowNLP、ggplot、pandas
前面代码块未出现问题,最后绘制可视化图形时,出现报错,图像不显示,排查后主要原因是ggplot版本和pandas不兼容问题,通过文末方法解决。
#!/usr/bin/env python
# coding: utf-8
# In[1]:
#导入评价数据
import pandas as pd
df = pd.read_excel('/Users/Desktop/临时文件/restaurant-comments.xlsx')
df.head() #读取数据内容
# In[2]:
text = df.comments.iloc[0]
from snownlp import SnowNLP
s = SnowNLP(text)
s.sentiments #显示SnowNlP分析结果
# In[3]:
def get_sentiment_cn(text):
s = SnowNLP(text)
return s.sentiments
# In[ ]:
#使用apply分别对每一条评价进行情感分析,并将分析结果增加到sentiment列
df['sentiment'] = df.comments.apply(get_sentiment_cn)
df.head()
# In[ ]:
#查看情感分析总结果
df.sentiment.mean()
# In[ ]:
#查看情感分析结果中位数
df.sentiment.median()
# In[ ]:
#使用ggplot可视化
get_ipython().run_line_magic('pylab', 'inline')
from ggplot import *
ggplot(aes(x='date', y = 'sentiment'), data = df) + geom_point() + geom_line(color = 'blue')+ scale_x_date(labels = date_format('%Y-%m-%d'))
# In[ ]:
#将Jupyter Noterbook代码块生成Py文件
try:
get_ipython().system('jupyter nbconvert --to python restaurant-comments')
except:
pass
结果
整体结果来看,大部分顾客对火锅店还是比较满意的,对于少数异常点可以通过可视化图形进行排查。
使用ggplot绘制图形时,Jupyter Notebook报错如下:
绘制结果
上述解决方法:报错:AttributeError: module ‘pandas’ has no attribute ‘tslib’ 的解决方法



