-
Notifications
You must be signed in to change notification settings - Fork 1
/
02-data-process.py
219 lines (148 loc) · 4.52 KB
/
02-data-process.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import os
import copy
import string
import json
import time
import random
import argparse
from nltk.corpus import stopwords
stop_words = set(stopwords.words('english'))
special_chars = ['#', '*', '~', '!',
'@', '$', '%', '^',
'&', '(', ')', '+',
'[', ']', '{', '}',
'.', '/', '-', '<',
'>', '?', ':', ';',
'`', ' ']
parser = argparse.ArgumentParser()
parser.add_argument("dataset")
args = parser.parse_args()
dataset = args.dataset
# In[ ]:
def chunk(lst, n):
p = 0
cnt = len(lst)
tmp = []
for i in range(n-1):
interval = int(cnt/(n-i)) + 1
tmp.append(lst[p:p+interval])
p+=interval
cnt-=interval
tmp.append(lst[p:len(lst)])
return tmp
# In[ ]:
def checkValidString(st):
for char in special_chars:
if char in st:
return False
if not st[0].isalpha():
return False
return True
# In[ ]:
cur_dir = os.path.join(os.getcwd())
entity2id_path = os.path.join(cur_dir, "data", dataset, "intermediate", "entity2id.txt")
eid2skipgram_path = os.path.join(cur_dir, "data", dataset, "intermediate", "reduced_eidSkipgramCounts.txt")
w2v_path = os.path.join(cur_dir, "data", dataset, "intermediate", "w2v.txt")
cleaned_entity2id_path = os.path.join(cur_dir, "data", dataset, "intermediate", "cleaned_entities2eid.json")
# In[ ]:
entity2eid = {}
with open(entity2id_path, 'r', encoding='utf-8') as fin:
data = fin.readlines()
for line in data:
splits = line.split('\t')
entity2eid[splits[0]] = splits[1].strip('\n')
lst = []
for ent in list(entity2eid.keys()):
if not checkValidString(ent):
lst.append(ent)
filtered_entity2eid = copy.deepcopy(entity2eid)
for ent in lst:
del filtered_entity2eid[ent]
print(len(entity2eid), len(filtered_entity2eid))
# In[ ]:
w2v_ent = []
with open(w2v_path, 'r') as fin:
lines = fin.readlines()[1:]
for line in lines:
w2v_ent.append(line.split()[0])
# In[ ]:
good_entities = set(list(filtered_entity2eid.keys())).intersection(w2v_ent)
# In[ ]:
good_eids = [entity2eid[x] for x in good_entities]
print(len(good_eids))
# In[ ]:
cleaned_entity2id = {k:filtered_entity2eid[k] for k in good_entities}
len(cleaned_entity2id)
# In[ ]:
with open(cleaned_entity2id_path, 'w+') as fout:
json.dump(cleaned_entity2id, fout)
# In[ ]:
fin = open(eid2skipgram_path, 'r', encoding='utf-8')
data = fin.readlines()
# In[ ]:
dct = {}
print("#records: " + str(len(lines)))
for line in data:
seg = line.strip("\r\n").split("\t")
eid = seg[0]
skipgram = seg[1]
count = int(seg[2])
if skipgram not in dct:
dct[skipgram] = {}
dct[skipgram][eid] = count
else:
if eid in dct[skipgram]:
dct[skipgram][eid] += count
else:
dct[skipgram][eid] = count
print("#skipgrams: " + str(len(dct)))
# In[ ]:
skipgram2both = {}
for skip in dct:
mention = 0
entities = 0
subdict = dct[skip]
for ent in subdict:
entities += 1
mention += subdict[ent]
skipgram2both[skip] = [entities, mention]
print(len(skipgram2both))
filtered_skipgram2both = {}
for skip in skipgram2both:
if skipgram2both[skip][0] > 10 and skipgram2both[skip][1] > 30:
filtered_skipgram2both[skip] = skipgram2both[skip]
print(len(filtered_skipgram2both))
good_skips = [x.strip() for x in list(filtered_skipgram2both.keys())]
# In[ ]:
good_skips[:5]
# In[ ]:
eidskipgramcounts = {}
skipgram2sid = {}
idx = 0
cnt = 0
ttl = 0
start = time.time()
for line in data:
ttl += 1
splits = line.strip('\n').split('\t')
if splits[0] in good_eids and splits[1].strip() in good_skips:
cnt += 1
sg = splits[1].strip()
if sg not in skipgram2sid:
skipgram2sid[sg] = idx
eidskipgramcounts["{},{}".format(splits[0], idx)] = int(splits[2])
idx += 1
else:
eidskipgramcounts["{},{}".format(splits[0], skipgram2sid[sg])] = int(splits[2])
if cnt % 1000 == 0:
end = time.time()
print("{} / {} records filtered... {:.2f} seconds elapsed...".format(cnt, ttl, end-start))
start = time.time()
# In[ ]:
with open('data/{}/intermediate/cleaned_eidskipgramcounts.json'.format(dataset), 'w+') as fout:
json.dump(eidskipgramcounts, fout)
with open('data/{}/intermediate/skipgram2sid.json'.format(dataset), 'w+') as fout:
json.dump(skipgram2sid, fout)