-
Notifications
You must be signed in to change notification settings - Fork 1
/
degree.py
244 lines (203 loc) · 8.55 KB
/
degree.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
from SPARQLWrapper import SPARQLWrapper
import networkx as nx
from tqdm import tqdm
def get_data(query,res_format):
sparql = SPARQLWrapper("https://dbpedia.org/sparql/")
sparql.setQuery(query)
sparql.setReturnFormat(res_format)
try:
ret = sparql.query().convert()
return ret
except:
#deal_with_the_exception()
#print("there's somthing wrong!\n")
return 0
def clean_center_word(subject_):
subject_replace = ''
for i in subject_:
if i.isalnum():
subject_replace += i
elif i == ' ':
subject_replace += '_'
else:
subject_replace = subject_replace +'\\' +i
return subject_replace
key = ['http://dbpedia.org/ontology/','http://dbpedia.org/resource/','http://dbpedia.org/property/']
value_type_skip = ['typed-literal'] #多为时间数字等;这两者都对于度计算时,没有意义;但实际上他们可以提供非常丰富的语料信息,【本质问题感觉是没有考虑边属性】
class get_by_degree:
'''
1. 去除不合格前缀网址及wiki
2. 去除不合格类型
3. 对于一个点,二者之间可能有多种关系,要将关系合并后再将边放入graph
'''
def __init__(self,center_word = None, escape = True,num = 10,res_format = 'json'):
self.center_word = center_word #the recent center word
self.escape = escape #whether to escape thr key
self.query = "" # for sql
self.top_k = num #nums to show the entities
self.format = res_format #reutrn format
def _get_query(self,center_word,is_for_expand):
if not is_for_expand:
self.query =[
f'''
prefix dbo:<http://dbpedia.org/ontology/>
prefix dbr:<http://dbpedia.org/resource/>
SELECT ?property ?value
Where {{
dbr:{self.center_word} ?property ?value
}}
'''
,
f'''
prefix dbo:<http://dbpedia.org/ontology/>
prefix dbr:<http://dbpedia.org/resource/>
SELECT ?value ?property
Where {{
?value ?property dbr:{self.center_word}
}}
'''
]
else:
center_word = clean_center_word(center_word)
self.query = [f'''
prefix dbo:<http://dbpedia.org/ontology/>
prefix dbr:<http://dbpedia.org/resource/>
SELECT COUNT(?label ) as ?num
Where{{
dbr:{center_word} ?label ?value
}}
'''
,
f'''
prefix dbo:<http://dbpedia.org/ontology/>
prefix dbr:<http://dbpedia.org/resource/>
SELECT COUNT(?label ) as ?num
Where{{
?value ?label dbr:{center_word}
}}
''']
def _clean_data(self,data):
'''
can use filter to speed up the process
'''
w = []
for i in data["results"]["bindings"]:
if i['property']['value'].startswith(key[0]) or i['property']['value'].startswith(key[1]) or i['property']['value'].startswith(key[2]):
if i['value']['type'] in value_type_skip:
continue
if i['value']['type'] == 'uri':
v = i['value']['value'].split('/')[-1]
elif i['value']['type'] == 'literal' and i['value']['xml:lang'] == "en" and i['value']['value']!= "": #注意有为空的情况
v = i['value']['value']
else:
continue
l = i['property']['value'].split('/')[-1]
if l.startswith('wiki'): #escape wiki in dbo
continue
if len(w)>0 and v in w: #yhe entity has been recorded
continue
else:
if v == self.center_word:
print(i)
continue
w.append(v)
return w
def _get_the_relationship(self,subject_,object_):
relationship = None
subject_ = clean_center_word(subject_)
object_ = clean_center_word(object_)
query = f'''
prefix dbo:<http://dbpedia.org/ontology/>
prefix dbr:<http://dbpedia.org/resource/>
SELECT ?property
Where {{
dbr:{subject_} ?property dbr:{object_}
}}
'''
data = get_data(query,self.format)
if data == 0: #they don't have realtionship from this direction
return None
for i in data["results"]["bindings"]:
l = i['property']['value'].split('/')[-1]#查看过其返回类型都是uri
if l.startswith('wiki'): #dbo中也有wiki
continue
if relationship == None:
relationship = l
else:
relationship =relationship+ '/'+ l
return relationship
def _get_data(self):
print("=== run the get data process ===== ")
self._get_query(self.center_word,False)
data = get_data(self.query[0],self.format) # 作主语
if data == 0:
print(data)
w = []
else:
print(len(data))
print(f'[!] as the subject: num = {len(data["results"]["bindings"])}')
#print(len(data))
if self.escape:
w = self._clean_data(data)
else:
w = data["results"]["bindings"]
print(f'[!] as the subject after cleanning: num = {len(w)}')
data = get_data(self.query[1],self.format) # 作宾语
if data == 0:
print(f'[!] as the object: num = {data}')
w_ = []
else:
print(f'[!] as the object: num = {len(data["results"]["bindings"])}')
if self.escape:
w_ = self._clean_data(data)
else:
w_ = data["results"]["bingdings"]
print(f'[!] as the object after cleanning: num = {len(w_)}')
w = w + w_
w = list(set(w))
# call _get_the_top10_by_degree()
w = self._get_the_topk_by_degree(w,self.top_k)
edges,nodes=self._get_nodes_edges(w)
return edges,nodes
def _get_the_topk_by_degree(self,words,top_k=10):
w = []
total_degree = 0
for i in tqdm(range(len(words))):
self._get_query(words[i],True)
res = get_data(self.query[0],self.format)#as object, outdegree
if res != 0:
num =int(res["results"]["bindings"][0]["num"]["value"])
else:
num = 0
res = get_data(self.query[1],self.format)#as subject,in_degree
if res != 0:
num +=int(res["results"]["bindings"][0]["num"]["value"])
else:
num += 0
total_degree += num
w.append({'value':words[i],'degree':num})
print('degree\n',sorted(w,key=lambda k:k['degree'],reverse=True))
print('total_degree\n',total_degree)
w = sorted(w,key=lambda k:k['degree'],reverse=True)[:top_k]
return w
def _get_nodes_edges(self,words):
edges = []
nodes = []
nodes.append((self.center_word,{'value':self.center_word.replace('_',' ')})) #避免显示的困扰
for w in words:
nodes.append((w['value'],{'value':w['value'].replace('_',' ')}))#避免显示的困扰
relationship = self._get_the_relationship(subject_=self.center_word,object_=w['value'])
if relationship != None:
edges.append((self.center_word,w['value'],{'property':relationship}))#center-> entity
else:
relationship_ =self._get_the_relationship(subject_=w['value'],object_=self.center_word)
if relationship_ != None:
edges.append((w['value'],self.center_word,{'property':relationship_}))#entity->center
else:# relationship == None and relationship_ == None:
#print(f'[!] all none :{self.center_word} {w["value"]}')
continue
return edges,nodes
def _change_center_word(self,center_word):
center_word = clean_center_word(center_word)
self.center_word = center_word
print(self.center_word)