-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwikiinfo.py
380 lines (336 loc) · 12.1 KB
/
wikiinfo.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
"""
Author: Willem Hengeveld <itsme@xs4all.nl>
Tool for extracting properties from a list of pages, and output them
in a table.
python3 wikiinfo --pages "Venus,Mars,Mercury,Earth" --properties "
"""
import re
def parsehtmltoken(token):
"""
parses a html token : <tag attrs...>
returns: tag, undecoded-attr-string
"""
m = re.match(r'<\s*(\w+)(.*?)/?>', token)
if m:
return m.group(1), m.group(2)
print("ERROR invalid html: %s" % token)
class WikiParser:
"""
Decode a mediawiki text containing of the following elements:
{{command | ... }}
{{{...}}}
[[pagename | ... ]]
[externallink description]
<tag>...</tag>
<element key=value ... />
{| ... |} -- table
<!-- ... -->
"""
class WikiTable:
"""
{| ... |}
"""
def __init__(self, contents):
self.contents = contents
def matches(self, token):
return False
def __repr__(self):
return "Table: {| %s |}" % self.contents
class WikiItem:
"""
{{{ ... }}}
"""
def __init__(self, token, contents):
self.token = token
self.contents = contents
def matches(self, token):
return False
def inversetoken(self):
if self.token.startswith("{"):
return "}" * len(self.token)
if self.token.startswith("["):
return "]" * len(self.token)
return "???"
def __repr__(self):
return "Wiki: %s %s %s" % (self.token, self.contents, self.inversetoken())
class HtmlTag:
"""
<tag k=v ...>
"""
def __init__(self, tag, attr):
self.tag = tag
self.attr = attr
def matches(self, token):
return re.match(r'</\s*%s\s*>' % self.tag, token) is not None
def __repr__(self):
return "Html: <%s %s>" % (self.tag, self.attr)
class HtmlElem:
"""
<tag k=v />
or
<tag k=v > ... </tag>
"""
def __init__(self, tag, attr, data = None):
self.tag = tag
self.attr = attr
self.data = data
def matches(self, token):
return False
def __repr__(self):
return "Html: <%s %s>%s</%s>" % (self.tag, self.attr, self.data, self.tag)
class Open:
"""
{, {{, {{{, [, [[, {|
"""
def __init__(self, token):
self.token = token
def matches(self, token):
if self.token == "{|" and token == "|}":
return True
if len(self.token) > len(token):
return False
if self.token.startswith("{") and token.startswith("}"):
return True
if self.token.startswith("[") and token.startswith("]"):
return True
return False
def __repr__(self):
return "Open: %s" % (self.token)
class WikiData:
def __init__(self, data):
self.data = data
def matches(self, token):
return False
def __repr__(self):
return "Data: %s" % (self.data.encode('utf-8'))
class Comment:
def __init__(self, data):
self.data = data
def matches(self, token):
return False
def __repr__(self):
return "Comment: %s" % (self.data)
def __init__(self):
self.stack = []
def feed(self, text):
M = re.compile(r'{\| | \|}+ | \[+ | \]+ | {+ | }+ | <!--.*?--> | </?\w+[^>]*>', flags=re.X|re.S)
o = 0
while o < len(text):
m = M.search(text, o)
if not m:
self.stack.append(self.WikiData(text[o:]))
break
if o < m.start():
self.stack.append(self.WikiData(text[o:m.start()]))
token = m.group(0)
o = m.end()
if token == "{|":
self.stack.append(self.Open(token))
elif token == "|}}":
if isinstance(self.stack[-1], self.WikiData):
self.stack[-1].data += "|"
wikiitem = self.close("}}")
if wikiitem:
self.stack.append(self.WikiItem(wikiitem[0].token, wikiitem[1:]))
else:
print("ERROR: no close1 | }} at %d - %s : %s" % (o, token, text[o-16:o+16].encode('utf-8')))
elif token == "|}":
table = self.close(token)
self.stack.append(self.WikiTable(table))
elif token.startswith("{") or token.startswith("["):
self.stack.append(self.Open(token))
elif token.startswith("}") or token.startswith("]"):
# these should all work:
# { { }}
# {{{ }}}
# {{ {{ }}}}
# {{ { }}}
# --> find most recent opening bracket, and close it with the right mount of closing brackets.
while token:
wikiitem = self.close(token)
if not wikiitem:
print("ERROR - no close for '%s' at %d: %s" % (token, o, text[o-16:o+16].encode('utf-8')))
break
opentoken = wikiitem[0].token
self.stack.append(self.WikiItem(wikiitem[0].token, wikiitem[1:]))
token = token[len(opentoken):]
elif token.startswith("</"):
# html close tag
htmlelem = self.close(token)
if htmlelem:
htmlopen = htmlelem[0]
htmlcontent = htmlelem[1:]
self.stack.append(self.HtmlElem(htmlopen.tag, htmlopen.attr, htmlcontent))
else:
print("ERROR - no close for '%s' at %d: %s" % (token, o, text[o-32:o+32].encode('utf-8')))
elif token.startswith("<!--"):
# comment tag
self.stack.append(self.Comment(token))
elif token.startswith("<") and token.endswith("/>"):
# single <tag ..../> element
tag, attr = parsehtmltoken(token)
self.stack.append(self.HtmlElem(tag, attr))
elif token.startswith("<") and token.endswith(">"):
# opening <tag ....>
tag, attr = parsehtmltoken(token)
# special handling for <math>, <nowiki>, <noinclude>
if tag in ('math', 'nowiki', 'noinclude'):
ET = re.compile(r'</\s*%s\s*>' % tag)
m = ET.search(text, o)
if not m:
print("ERROR - expected </%s> after %d" % (tag, o))
else:
self.stack.append(self.HtmlElem(tag, attr, text[o:m.start()]))
o = m.end()
else:
self.stack.append(self.HtmlTag(tag, attr))
else:
print("Unknown token: %s" % token)
def close(self, token):
"""
returns enclosed items.
or None when no opening bracket found.
"""
popped = []
while self.stack:
item = self.stack.pop()
popped.append(item)
if item.matches(token):
return popped[::-1]
self.stack = popped[::-1]
def parseWikitext(wikitext):
w = WikiParser()
w.feed(wikitext)
return w.stack
def findTemplate(tree, templatename):
for item in tree:
if isinstance(item, WikiParser.WikiItem):
if isinstance(item.contents[0], WikiParser.WikiData):
if item.contents[0].data.startswith(templatename):
return item.contents
def findAllTemplates(tree, templatename):
for item in tree:
if isinstance(item, WikiParser.WikiItem):
if isinstance(item.contents[0], WikiParser.WikiData):
if item.contents[0].data.startswith(templatename):
yield item.contents
def parseInfobox(ibox):
"""
{{Infobox boxname
| propname = {{plainlist | {{val | <value> }} }}
}}
returns a dictionary of key/value pairs
"""
records = []
def addtext(txt):
if type(records[-1][-1]) == str:
# join consequetive string items.
records[-1][-1] += txt
else:
records[-1].append(txt)
for item in ibox:
if isinstance(item, WikiParser.WikiData):
f = item.data.split("|")
if item.data[:1] != "|" and records:
addtext(f[0])
del f[0]
for x in f:
records.append([x])
elif isinstance(item, WikiParser.WikiItem) \
or isinstance(item, WikiParser.HtmlElem):
records[-1].append(item)
else:
# .. todo: ignore comment
#print("??? - %s" % item)
pass
d = dict()
for rec in records:
m = re.match(r'^\s*([^=]+)\s*=\s*(.*)', rec[0])
if not m:
# todo: ignore infobox header
#print("!!! - %s" % rec)
pass
else:
k = m.group(1)
v0 = m.group(2)
rec[0] = v0
if not v0:
del rec[0]
d[k] = rec
#for k, v in d.items():
# print("\t%-30s\t%s" % (k, v))
return d
def extractValue(valuelist):
if not valuelist:
return
for item in valuelist:
if isinstance(item, WikiParser.WikiItem) and item.token == "{{":
# recurse
v = extractValue(item.contents)
if v:
return v
# otherwise just return the string content
return item.contents
elif isinstance(item, WikiParser.WikiData):
base = None
exponent = 0
accuracy = None
isvalue = None
for fld in item.data.split('|'):
if not fld:
continue
if fld == 'val':
isvalue = True
elif fld.startswith('fmt='):
pass
elif isvalue:
m = re.match(r'^(\w+)\s*=\s*(\S*)', fld)
if m:
if m.group(1) == 'e':
exponent = int(m.group(2))
elif m.group(1) in ('u', 'ul'):
unit = m.group(2)
else:
print("unknown value property: %s" % fld)
elif base is None:
base = float(fld)
elif accuracy is None:
accuracy = float(fld)
else:
print("value:", fld)
if isvalue:
return base * pow(10, exponent)
else:
# just return the value
return item
return
def getpage(language, pagename):
import urllib.request
import urllib.parse
req = urllib.request.Request("https://%s.wikipedia.org/wiki/" % language + urllib.parse.quote(pagename) + "?action=raw")
response = urllib.request.urlopen(req)
return response.read()
def main():
import argparse
parser = argparse.ArgumentParser(description='Extract tables of information from wikipedia.')
parser.add_argument('--language', '-l', type=str, help='Which wikipedia site to use.', default='en')
parser.add_argument('--pages', '-p', type=str, help='Which pages to search.')
parser.add_argument('--properties', '-q', type=str, help='Which properties to extract.')
args = parser.parse_args()
for pg in args.pages.split(","):
print("==>", pg, "<==")
try:
wikitext = getpage(args.language, pg)
tree = parseWikitext(wikitext.decode('utf-8'))
ibox = findTemplate(tree, "Infobox")
props = parseInfobox(ibox)
for p in args.properties.split(","):
print(extractValue(props.get(p)), end="\t")
print()
except Exception as e:
print(e)
import traceback
traceback.print_exc()
print()
if __name__ == '__main__':
main()