db/dic2csv.py
changeset 2 f1fc3afacfd6
child 4 140c907a66be
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/db/dic2csv.py	Wed Jun 25 18:48:18 2014 +0200
     1.3 @@ -0,0 +1,54 @@
     1.4 +#! /usr/bin/env python3
     1.5 +
     1.6 +from argparse import ArgumentParser
     1.7 +from fileinput import FileInput, hook_encoded
     1.8 +import re, itertools, sys
     1.9 +
    1.10 +try:
    1.11 +    from math import log2
    1.12 +except:
    1.13 +    from math import log
    1.14 +    def log2(x): return log(x) / log(2)
    1.15 +
    1.16 +word = re.compile(r"(\S*?)(/|\s.*|$)")
    1.17 +unwanted = re.compile(r"(^\d|[^']*')")
    1.18 +space = re.compile(r'^\s')
    1.19 +
    1.20 +p = ArgumentParser(description="create dictionary csv out of hunspell data")
    1.21 +p.add_argument('--hunspell', '-H', type=str, default="/usr/share/hunspell",
    1.22 +    help='directory where hunspell dictionary files reside (default: /usr/share/hunspell)')
    1.23 +p.add_argument('--lang', '-l', type=str, default="en_US",
    1.24 +    help='use dictionary for language LANG (default: en_US)')
    1.25 +p.add_argument('--encoding', '-e', type=str, default="utf-8",
    1.26 +    help='file encoding (default: utf-8)')
    1.27 +
    1.28 +args = p.parse_args()
    1.29 +
    1.30 +_all = (
    1.31 +    word.match(line).group(1).upper()
    1.32 +        for line in FileInput(
    1.33 +                args.hunspell + "/" + args.lang + ".dic",
    1.34 +                openhook=hook_encoded(args.encoding)
    1.35 +            )
    1.36 +        if not space.match(line)
    1.37 +)
    1.38 +_words = [w for w in _all if len(w) > 2 and not unwanted.match(w)]
    1.39 +_words.sort()
    1.40 +_words = [w for w, g in itertools.groupby(_words)]
    1.41 +
    1.42 +if len(_words) > 65536:
    1.43 +    _words = _words[:65536]
    1.44 +elif len(_words) < 65536:
    1.45 +    sys.stderr.write(
    1.46 +            "warning for {}: only {:.2f} bit in wordlist, that makes {:.2f} bit for 5 words\n".format(
    1.47 +                    args.lang,
    1.48 +                    log2(len(_words)),
    1.49 +                    log2(len(_words))*5
    1.50 +                )
    1.51 +        )
    1.52 +    _words.extend(_words[:65536-len(_words)])
    1.53 +
    1.54 +assert len(_words) == 65536, "lenght is {}".format(len(_words))
    1.55 +
    1.56 +for i, w in enumerate(_words):
    1.57 +    print("{l},{i},{w}".format(l=args.lang[:2], i=i, w=w))