forked from BinLiang-NLP/Sentic-GCN
-
Notifications
You must be signed in to change notification settings - Fork 2
/
sentic_dependency_graph_abs.py
executable file
·82 lines (72 loc) · 2.57 KB
/
sentic_dependency_graph_abs.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# -*- coding: utf-8 -*-
import numpy as np
import spacy
import pickle
nlp = spacy.load('en_core_web_sm')
def load_sentic_word():
"""
load senticNet
"""
path = './senticNet/senticnet_word.txt'
senticNet = {}
fp = open(path, 'r')
for line in fp:
line = line.strip()
if not line:
continue
word, sentic = line.split('\t')
senticNet[word] = sentic
fp.close()
return senticNet
def dependency_adj_matrix(text, aspect, senticNet):
# https://spacy.io/docs/usage/processing-text
document = nlp(text)
seq_len = len(text.split())
matrix = np.zeros((seq_len, seq_len)).astype('float32')
#print('='*20+':')
#print(document)
#print(senticNet)
for token in document:
#print('token:', token)
if str(token) in senticNet:
sentic = abs(float(senticNet[str(token)])) + 1
else:
sentic = 1
if str(token) in aspect:
sentic += 1
if token.i < seq_len:
matrix[token.i][token.i] = 1 * sentic
# https://spacy.io/docs/api/token
for child in token.children:
if str(child) in aspect:
sentic += 1
if child.i < seq_len:
matrix[token.i][child.i] = 1 * sentic
matrix[child.i][token.i] = 1 * sentic
return matrix
def process(filename):
senticNet = load_sentic_word()
fin = open(filename, 'r', encoding='utf-8', newline='\n', errors='ignore')
lines = fin.readlines()
fin.close()
idx2graph = {}
fout = open(filename+'.graph_sdat_abs', 'wb')
for i in range(0, len(lines), 3):
text_left, _, text_right = [s.lower().strip() for s in lines[i].partition("$T$")]
aspect = lines[i + 1].lower().strip()
adj_matrix = dependency_adj_matrix(text_left+' '+aspect+' '+text_right, aspect, senticNet)
idx2graph[i] = adj_matrix
pickle.dump(idx2graph, fout)
print('done !!!'+filename)
fout.close()
if __name__ == '__main__':
process('./datasets/acl-14-short-data/train.raw')
process('./datasets/acl-14-short-data/test.raw')
process('./datasets/semeval14/restaurant_train.raw')
process('./datasets/semeval14/restaurant_test.raw')
process('./datasets/semeval14/laptop_train.raw')
process('./datasets/semeval14/laptop_test.raw')
process('./datasets/semeval15/restaurant_train.raw')
process('./datasets/semeval15/restaurant_test.raw')
process('./datasets/semeval16/restaurant_train.raw')
process('./datasets/semeval16/restaurant_test.raw')