mrzjy commited on
Commit
80a3efc
1 Parent(s): a7a096b

Upload preprocess_wiki_xml.py

Browse files
Files changed (1) hide show
  1. preprocess_wiki_xml.py +68 -0
preprocess_wiki_xml.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+
3
+ import mwxml
4
+ from mwxml.errors import MalformedXML
5
+ from tqdm import tqdm
6
+
7
+ """
8
+ fix the error in the lines below, before running the script:
9
+ xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 23871045, column 4
10
+ """
11
+
12
+ # specify the data path here
13
+ file_path = "path/to/your-history.xml"
14
+
15
+ raw_data = []
16
+
17
+ import xml.etree.ElementTree as ET
18
+
19
+
20
+ def strip_tag_name(t):
21
+ t = elem.tag
22
+ idx = k = t.rfind("}")
23
+ if idx != -1:
24
+ t = t[idx + 1:]
25
+ return t
26
+
27
+
28
+ if __name__ == '__main__':
29
+ count = 0
30
+ prev_title = ""
31
+ current_data = None
32
+ ns = ""
33
+
34
+ # get an iterable
35
+ context = ET.iterparse(file_path, events=("start", "end"))
36
+
37
+ # turn it into an iterator
38
+ context = iter(context)
39
+
40
+ # get the root element
41
+ event, root = next(context)
42
+
43
+ with open("raw_data.jsonl", "w", encoding="utf-8") as f:
44
+ for event, elem in tqdm(context):
45
+ tname = strip_tag_name(elem.tag)
46
+
47
+ if event == 'end':
48
+ if tname == 'title':
49
+ title = elem.text
50
+ if tname == "ns":
51
+ ns = elem.text
52
+ elif tname == 'text':
53
+ content = elem.text
54
+ if ns == "0" and content: # only namespace = "0" is what we need
55
+ # only account for the latest
56
+ if title != prev_title and current_data:
57
+ print(json.dumps(current_data, ensure_ascii=False), file=f)
58
+ count += 1
59
+ if count % 1000 == 0:
60
+ print(count)
61
+
62
+ prev_title = title
63
+ current_data = {
64
+ "title": title,
65
+ "content": content,
66
+ }
67
+
68
+ root.clear()