需求
通过已有数据文件(链接: 数据文件来源.)拿到数据,筛选毒菌相关的我的评论,并使用matplotlib.pyplot画出筛选后的评论按日期分布折线图,实现数据可视化
代码
import datetime
import re
import matplotlib.pyplot as plt
first_date, last_date = '2020-01-01', '2020-11-01'
def comm_msg(path):
day_num = (datetime.datetime.strptime(last_date, '%Y-%m-%d') -
datetime.datetime.strptime(first_date, '%Y-%m-%d')).days + 1 # 总天数
data_dict = dict([((datetime.datetime.strptime(first_date, '%Y-%m-%d') +
datetime.timedelta(days=i)).strftime('%m.%d'), 0) for i in range(day_num)])
super_poisonous_mushrooms = ['青褶伞', '日本红菇', '盔孢伞', '卷边桩菇', '黄盖鹅膏', '肉褐鳞环柄菇', '亚稀褶红菇',
'鹿花菌', '丝盖伞']
poisonous_regular_strs = ['[^没无]毒|^毒', '头晕|头痛', '腹泻|肠胃炎', '[^牛]肝|^肝', '肾[^形]|肾$', '内脏损伤',
'致命|要命|生命危险', '|'.join(super_poisonous_mushrooms)]
with open(path, 'r', encoding='utf-8') as f:
for l in f:
l = l.split('\t')
comm_time, comm_text = l[3], l[2]
if comm_time.startswith('2020'):
matched_str = comm_text.split('</a>:')[-1]
if '</a>:' in matched_str:
matched_str = comm_text.split('</a>:')[-1] # 防止被回答者id带关键字
for prs in poisonous_regular_strs: # 是否符合任一条目标正则
if re.findall(prs, matched_str):
data_dict[comm_time.replace('-', '.')[5:10]] += 1 # 筛过处理
break
return list(data_dict.keys()), list(data_dict.values())
plt.rcParams['font.sans-serif'] = ['simsun'] # 宋体
x_date_data, y_comm_data = comm_msg(r'D:\xxx\data.txt')
interval_x = 20 # 隔几单位显示一次日期
plt.xticks(range(len(x_date_data)), [x_date_data[i] if i % interval_x == 0 else ' ' for i in range(len(x_date_data))]) # x轴日期标注
plt.axis([-1, len(x_date_data), 0, ((max(y_comm_data) - 1) // 10 + 1) * 10]) # 横纵坐标边界
plt.grid() # 网格
plt.plot(x_date_data, y_comm_data, c='red')
plt.legend(['涉及毒菌评论总数'], loc='upper left')
plt.show()
效果图: