0/参考网址
https://blog.csdn.net/hzp666/article/details/78969150
1/数据:
1/鹿晗微博3万条评论;
2/关晓彤微博3万条评论;
3/500万微博语料,下载地址,密码:tvdo
2/工具:
1/Python3.6
2/SnowNLP
https://github.com/isnowfy/snownlp
可方便的处理中文文本内容,是受到了TextBlob的启发而写的,
由于现在大部分的自然语言处理库基本都是针对英文的,于是写了一个方便处理中文的类库,
并且和TextBlob不同的是,这里没有用NLTK,所有的算法都是自己(不是本人)实现的,并且自带了一些训练好的字典。)
3/WordCloud,词云。
3/具体实例实施过程
<1>下载微博500万条记录,一定要到数据库所在机器上导入。
mysql - u root -p xxx <weibo500w.sql
<2>导入的时间会持续很长时间,导入完成后,为了提高效率可以进行去重和清理空的数据。
去重复内容:
delete from 表名 where id not in (select minid from (select min(id) as minid from 表名 group by 字段) b);
去值为NULL:
delete from 表名 where 字段名=NULL
去值为""空值
delete from 表名 where 字段名=''
<3>对微博语料进行情感分类,可以基于原有SnowNLP进行积极和消极情感分类和训练。
import re
from snownlp import sentiment
import numpy as np
import pymysql
from snownlp import SnowNLP
import matplotlib.pyplot as plt
from snownlp import sentiment
from snownlp.sentiment import Sentiment
# 连接数据库
conn = pymysql.connect(host='数据库IP',
user='用户名',
password='密码',
charset="utf8",
use_unicode=False)
with conn:
cur = conn.cursor()
cur.execute("SELECT * FROM test.weibo WHERE weiboId < '%d'" % 6000000)
rows = cur.fetchall()
comment = []
for row in rows:
row = list(row)
comment.append(row[18])
def train_model(texts):
for li in texts:
comm = li.decode('utf-8')
text = re.sub(r'(?:回复)?(?://)?@[\w\u2E80-\u9FFF]+:?|\[\w+\]', ',',comm)
socre = SnowNLP(text) # 对于每一行进行打分
if socre.sentiments > 0.8: # 如果分数>0.8,则是正面的评价
with open('pos.txt', mode='a', encoding='utf-8') as g:
g.writelines(comm +"\n")
elif socre.sentiments < 0.3: # 如果分数<0.3,则是负面的评价
with open('neg.txt', mode='a', encoding='utf-8') as f:
f.writelines(comm + "\n")
else: # 介于这个分数之间的,则是中性的评价
pass
train_model(comment)
sentiment.train('neg.txt', 'pos.txt')
sentiment.save('sentiment.marshal')
#训练完成后会生成sentiment.marshal.3,将snownlp/sentiment/中sentiment.marshal.3直接替换,训练可以进行多轮训练,精度会更好。
<4>爬取两人的微博数据,
使用http://m.weibo.com,解决懒加载问题,具体方式不在赘述,google 一下吧。