-
Notifications
You must be signed in to change notification settings - Fork 3
/
zim_extract_all.py
80 lines (73 loc) · 2.29 KB
/
zim_extract_all.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
# -*- coding: utf-8 -*-
import codecs
import re
import os
import argparse
from collections import Counter
from zimply.zimply import ZIMFile
# gather arguments
parser = argparse.ArgumentParser(
description="Extract per-language lemma list from zim file."
)
parser.add_argument(
"-zimfile", action="store", dest="zimfile", help="Location of ZIM file."
)
parser.add_argument(
"-langfile", action="store", dest="langfile", help="List of languages."
)
args = parser.parse_args()
# load the zimfile
zimfile = ZIMFile(args.zimfile, "utf-8")
# load the languages
with codecs.open(args.langfile, "rb", "utf-8") as f:
languages = [line.strip() for line in f]
# create directories to store results
for language in languages:
if not os.path.exists("./candidate_pages/" + language):
os.makedirs("./candidate_pages/" + language)
count = 0
cclust = 0
cblob = 0
OK = True
while OK:
try:
data = zimfile._read_blob(cclust, cblob)
count += 1
try:
body = data.decode("utf-8")
for language in languages:
if (
u">" + language + u"</h2>" in body
and (
u"Noun</h3>" in body
or u"Verb</h3>" in body
or u"Adjective</h3>" in body
or u"Pronoun</h3>" in body
)
and (
u"Conjugation" in body
or u"Declension" in body
or u"Inflection" in body
)
):
outf = codecs.open(
"./candidate_pages/"
+ language
+ "/candidate_"
+ str(count)
+ ".html",
"wb",
encoding="utf-8",
)
outf.write(body)
outf.close()
# update id
count += 1
except:
print("BAD DATA", count)
cblob += 1 # Update blob
except IOError:
cblob = 0 # reset blob
cclust += 1 # update cluster
if cclust >= zimfile.header_fields["clusterCount"]: # no such cluster anymore
OK = False