This repository has been archived by the owner on Apr 24, 2020. It is now read-only.
forked from faraday/wikiprep-esa
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathxmlwikiprep.py
71 lines (60 loc) · 2.23 KB
/
xmlwikiprep.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
try:
import cElementTree # this is manually installed
except:
import xml.etree.cElementTree as cElementTree
import sys
import string
"""
From project: wikiprep-postprocess
https://github.com/turian/wikiprep-postprocess
written by Joseph Turian
"""
def read(f, ignore_tags=None):
"""
Generator for reading a wikiprep XML file from a file object.
"""
print >> sys.stderr, "Reading %s..." % f
# print >> sys.stderr, stats()
doc = {}
cnt = 0
if not ignore_tags:
ignore_tags = set()
for event, elem in cElementTree.iterparse(f):
if elem.tag in ignore_tags:
continue
if elem.tag == "title":
doc["title"] = ("".join(elem.itertext()))
elif elem.tag == "text":
doc["text"] = ("".join(elem.itertext()))
elif elem.tag == "link":
# Skip internal links
if elem.get("url") is None:
continue
if "external links" not in doc:
doc["external links"] = []
doc["external links"].append([elem.get("url"), ("".join(elem.itertext()))])
elif elem.tag == "links":
doc["links"] = [int(i) for i in string.split("".join(elem.itertext()))]
elif elem.tag == "categories":
doc["categories"] = [int(i) for i in string.split("".join(elem.itertext()))]
elif elem.tag == "page":
doc["_id"] = int(elem.get("id"))
doc["length"] = int(elem.get("newlength"))
if elem.get("stub"):
doc["stub"] = bool(elem.get("stub") == "1")
if elem.get("disambig"):
doc["disambig"] = bool(elem.get("disambig") == "1")
if elem.get("image"):
doc["image"] = bool(elem.get("image") == "1")
if elem.get("category"):
doc["category"] = bool(elem.get("category") == "1")
cnt += 1
yield doc
doc = {}
# Free the memory of the building tree
elem.clear()
if cnt % 20000 == 0:
print >> sys.stderr, "Read %d articles from %s" % (cnt, f)
# print >> sys.stderr, stats()
print >> sys.stderr, "...done reading %s" % f
#print >> sys.stderr, stats()