forked from xszyou/Fay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
xf_ltp.py
59 lines (44 loc) · 1.4 KB
/
xf_ltp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import time
import urllib.request
import urllib.parse
import json
import hashlib
import base64
from utils import config_util as cfg
__URL = "https://ltpapi.xfyun.cn/v2/sa"
def __quest(text):
body = urllib.parse.urlencode({'text': text}).encode('utf-8')
param = {"type": "dependent"}
x_param = base64.b64encode(json.dumps(param).replace(' ', '').encode('utf-8'))
x_time = str(int(time.time()))
x_checksum = hashlib.md5(cfg.key_xf_ltp_api_key.encode('utf-8') + str(x_time).encode('utf-8') + x_param).hexdigest()
x_header = {
'X-Appid': cfg.key_xf_ltp_app_id,
'X-CurTime': x_time,
'X-Param': x_param,
'X-CheckSum': x_checksum
}
req = urllib.request.Request(__URL, body, x_header)
result = urllib.request.urlopen(req)
result = result.read()
return json.loads(result.decode('utf-8'))
"""
情感分析
:param text: 文本
:returns: 情感分数 (0.7以上为褒义, 0.3-0.7为中性 0.3以下为贬义,, -1为分析失败)
"""
def get_score(text):
result = __quest(text)
if result['desc'] == 'success':
return float(result['data']['score'])
return -1
"""
情感分析
:param text: 文本
:returns: 情感极性分类 (2为褒义, 1为中性 0为贬义,, -1为分析失败)
"""
def get_sentiment(text):
result = __quest(text)
if result['desc'] == 'success':
return int(result['data']['sentiment']) + 1
return -1