python情感分析
本篇博文將使用Python實現一個簡單的情感分析喔!
數據獲取
情感分析項目中我用到了三個數據集,分別如下:
(1)京東商城紅酒評價數據集 標籤數量 2 數據量 2,000
(2)生活微博數據集 標籤數量 4 數據量 40,000,
(3)英文推特數據集 標籤數量 11 數據量 210,000,
英文推特數據集生活微博數據集詞雲
(需要數據集的郵箱聯繫吧)!
這篇基本不會用到這三個
weibo數據集獲取API:
微博是我國最好的一個獲取情感語料的平臺之一,除了使用本書給定的數據集外,讀者可以嘗試自己爬取信息進行分析,微博的官方也給出了API,大家放心爬取評論就好。
首先給出一條爬取的評論的完整信息,也代表API的對象結構:
{
"comments": [
{
"created_at": "Wed Jun 01 00:50:25 +0800 2011",
"id": 12438492184,
"text": "love your work.......",
"source": "<a href="http://weibo.com" rel="nofollow">新浪微博</a>",
"mid": "202110601896455629",
"user": {
"id": 1404376560,
"screen_name": "zaku",
"name": "zaku",
"province": "11",
"city": "5",
"location": "北京 朝陽區",
"description": "人生五十年,乃如夢如幻;有生斯有死,壯士復何憾。",
"url": "http://blog.sina.com.cn/zaku",
"profile_image_url": "http://tp1.sinaimg.cn/1404376560/50/0/1",
"domain": "zaku",
"gender": "m",
"followers_count": 1204,
"friends_count": 447,
"statuses_count": 2908,
"favourites_count": 0,
"created_at": "Fri Aug 28 00:00:00 +0800 2009",
"following": false,
"allow_all_act_msg": false,
"remark": "",
"geo_enabled": true,
"verified": false,
"allow_all_comment": true,
"avatar_large": "http://tp1.sinaimg.cn/1404376560/180/0/1",
"verified_reason": "",
"follow_me": false,
"online_status": 0,
"bi_followers_count": 215
},
}
},
...
],
"previous_cursor": 0,
"next_cursor": 0,
"total_number": 7
}
其中劃線的句子是我們最需要的信息。那麼如何獲得這樣的評論,並且提取中其中的關鍵信息呢?
Python獲得weibo數據集:
這裏首先推薦一個Python的入門網站,對API和情感分析信息的獲取給出了不錯的介紹,
https://python123.io/tutorials/weibo_sentiment_anlysis
網頁上已經給出了教程,所以這裏不再贅述,附上完整源代碼:
import re
from typing import List
from pyecharts.charts import Map
from snownlp import SnowNLP
from weibopy import WeiboOauth2, WeiboClient
import webbrowser
mylog = open(r"C:\Users\ASUS\Desktop\weibo\nvpai.txt", mode='a', encoding='utf-8')
mylog2 = open(r"C:\Users\ASUS\Desktop\usr.txt", mode='a', encoding='utf-8')
mylog3 = open(r"C:\Users\ASUS\Desktop\province.txt", mode='a', encoding='utf-8')
client_key = '338653819' #
client_secret = 'b0e0de5e833ee45a63a9e99cd7e3c225' #
redirect_url = 'https://api.weibo.com/oauth2/default.html'
auth = WeiboOauth2(client_key, client_secret, redirect_url)
webbrowser.open_new(auth.authorize_url)
code = input('輸入 code:') # get code
# 使用 code 獲取 token
token = auth.auth_access(code)
print(token)
# token 是剛剛獲得的 token,可以一直使用
client = WeiboClient(token['access_token'])
from collections import defaultdict
import time
province_list = defaultdict(list) # 保存按省劃分的評論正文 what is list
comment_all_list = []
comment_text_list = [] # 保存所有評論正文
# 共獲取 10 頁 * 每頁最多 200 條評論
for i in range(1, 11):
result = client.get(suffix='comments/show.json', params={'id': 4318237070487349, 'count': 200, 'page': i})
#result = client.get(suffix='comments/show.json', params={'id': 4433173682894891, 'count': 200, 'page': i})
# attribute
comments = result['comments']
if not len(comments):
break
for comment in comments:
text = re.sub('回覆.*?:', '', str(comment['text']))
province = comment['user']['province']
province_list[province].append(text)
print(text, file=mylog)
comment_text_list.append(text)
print('已抓取評論 {} 條'.format(len(comment_text_list)))
# print(comment_text_list,file=mylog)
# print(province,file=mylog2)
# print(province_list,file=mylog3)
time.sleep(1)
provinces = {}
results = client.get(suffix='common/get_province.json', params={'country': '001'})
for prov in results:
for code, name in prov.items():
provinces[code] = name
print(provinces)
# 評論情感分析
# 評論情感分析
positives = {}
for province_code, comments in province_list.items():
sentiment_list = []
for text in comments:
s = SnowNLP(text)
sentiment_list.append(s.sentiments)
# 統計平均情感
positive_number = sum(sentiment_list)
positive = positive_number / len(sentiment_list) * 100
print(positive)
這個代碼唯一需要的就是微博的id,上面推薦的網站中也提到了獲取方法:微博 id 很容易獲得,只要打開一條微博,查看頁面的 URL,比如:
https://m.weibo.cn/detail/4321877356979717
後面的那串數字就是這條微博的id。以中國女排爲例,輸入其中任意一條微博的id,就可以得到輸出結果
詞彙分析
詞彙分析,簡單理解,就是對每一條預料進行分詞,使用stoptext(停詞表)去掉無用的詞,然後給每一個詞語賦予一個代表它的積極程度的評分(0-1),評分進行加權平均後,得到的最後score就是預料的評分。
對於詞彙分析最重要的是一個詞彙的評分表,這個表決定了每個單詞的得分,從而直接決定了最後句子的得分。Python中提供了不同種類的很多wordscore表,對初學者而言,建議SnowNLP庫:
SnowNLP是一個python寫的類庫,可以方便的處理中文文本內容,是受到了TextBlob的啓發而寫的,由於現在大部分的自然語言處理庫基本都是針對英文的,於是寫了一個方便處理中文的類庫,並且和TextBlob不同的是,這裏沒有用NLTK,所有的算法都是自己實現的,並且自帶了一些訓練好的字典。
當然,熟悉的讀者使用jieba,或者BaiduSenta也可以。
SnowNLP安裝及使用
安裝:
pip install snownlp
應用:
依次讀入每條數據進行賦分即可:
from snownlp import SnowNLP
mylog = open(r"C:\Users\ASUS\Desktop\weibo\niri.txt", mode='a', encoding='utf-8')
# 評論情感分析
f = open(r"C:\Users\ASUS\Desktop\weibo\nvpai.txt", 'r', encoding='utf-8')
line = f.readline()
sum=0
count=0
while line:
print(line)
s = SnowNLP(line)
print('{}'.format(s.sentiments))
#print(s.sentiments,mylog)
sum+=s.sentiments
count+=1
line = f.readline()
score=sum/count
print('finalscore={}'.format(score))
由此可以得到評分結果:
驕傲
0.96875
祝祖國和女排節日快樂
0.9952967295437758
hj
0.5
。
0.5262327818078083
🇨🇳
0.5
快來了
0.7164835164835165
快樂
0.9490740740740741
贊
0.9096018490786377
恭喜恭喜
0.890142453148024
你們最棒的
0.9579300380641783
太好了 恭喜大瓜隊 祝福祖國盛世華誕
0.9997137152019053
1
0.32689832689832665
最好的禮物🎁
0.8348113264121529
[鼓掌][饞嘴]
0.7399856276835112
至此,我想你已經可以對任何的微博評論進行爬取並進行詞彙評分分析。
京東紅酒數據分析
有了前面的鋪墊,我們就可以對京東的紅酒的評價信息的一個數據集進行分析得到如下結果:
公司用酒,還可以的,不錯
score: 0.7558598842353914
包裝很給力,唯獨就是灌裝日期是2016年的,希望口感還是一樣吧
score: 0.3574752433728978
很好
score: 0.7795229979671993
Hhhhhhhhhhhhhhhhhhh
score: 0.5
口味不錯,可以繼續購買。
score: 0.9617325918192866
這個系列的酒性價比都很高
score: 0.968043915479651
不錯
score: 0.8612132352941176
經常喝性價比比較高
score: 0.7355732591819286
好好好好好好好好好好好好好好好好
score: 0.8125455256644531
Neg dataset
木塞都沒有,勸大家不要買,小心上當
score: 0.0027557451026484214
買了你家這麼多東西還一號,打售後電話也不承認,搶了這麼天券,等到0點都不行,*
score: 0.0004998544973741081
瓶塞都沒有 很難喝假貨上當的感覺
score: 0.00893506581982595
送的袋子是個露的 麻煩以後檢查下再送 還不如不送 酒直接掉地上碎掉 呵呵
score: 0.008806432644460793
味道不咋樣,真心不如長城的。
score: 0.13623860106377927
二維碼竟然是爛的,這樣的貨也能發過來,以後不會再買了
score: 0.006946026588318555
木塞都沒有,勸大家不要買,小心上當
score: 0.0027557451026484214
買了你家這麼多東西還一號,打售後電話也不承認,搶了這麼天券,等到0點都不行,*
score: 0.0004998544973741081
可以看到pos dataset的評分和neg dataset的評分的對比,前者評分都在>0.5後者都在<0.01。
……待續