db/dic2csv.py
author vb
Mon, 23 Mar 2015 21:42:45 +0100
changeset 120 c282594b523b
parent 4 140c907a66be
child 121 dcefb3741425
permissions -rw-r--r--
case conversion including tailoring based on PyICU
     1 #! /usr/bin/env python3
     2 
     3 from argparse import ArgumentParser
     4 from fileinput import FileInput, hook_encoded
     5 import re, itertools, sys
     6 
     7 try:
     8     from math import log2
     9 except:
    10     from math import log
    11     def log2(x): return log(x) / log(2)
    12 
    13 word = re.compile(r"(\S*?)(/|\s.*|$)")
    14 unwanted = re.compile(r"(^\d|[^']*')")
    15 space = re.compile(r'^\s')
    16 
    17 p = ArgumentParser(description="create dictionary csv out of hunspell data")
    18 p.add_argument('--hunspell', '-H', type=str, default="/usr/share/hunspell",
    19     help='directory where hunspell dictionary files reside (default: /usr/share/hunspell)')
    20 p.add_argument('--lang', '-l', type=str, default="en_US",
    21     help='use dictionary for language LANG (default: en_US)')
    22 p.add_argument('--encoding', '-e', type=str, default="utf-8",
    23     help='file encoding (default: utf-8)')
    24 
    25 args = p.parse_args()
    26 
    27 try:
    28     from icu import UnicodeString, Locale
    29 except ImportError:
    30     print("warning: PyICU not installed, using fallback", file=sys.stderr)
    31     def upper(x):
    32         return x.upper();
    33 else:
    34     locale = Locale(args.lang)
    35     def upper(x):
    36         u = UnicodeString(x)
    37         return str(u.toUpper(locale))
    38 
    39 _all = (
    40     upper(word.match(line).group(1))
    41         for line in FileInput(
    42                 args.hunspell + "/" + args.lang + ".dic",
    43                 openhook=hook_encoded(args.encoding)
    44             )
    45         if not space.match(line)
    46 )
    47 _words = [w for w in _all if len(w) > 2 and not unwanted.match(w)]
    48 _words.sort()
    49 _words = [w for w, g in itertools.groupby(_words)]
    50 
    51 while len(_words) > 65536 * 2:
    52     _words = _words[::2]
    53 
    54 if len(_words) > 65536:
    55     _words = _words[:65536]
    56 elif len(_words) < 65536:
    57     sys.stderr.write(
    58             "warning for {}: only {:.2f} bit in wordlist, that makes {:.2f} bit for 5 words\n".format(
    59                     args.lang,
    60                     log2(len(_words)),
    61                     log2(len(_words))*5
    62                 )
    63         )
    64     _words.extend(_words[:65536-len(_words)])
    65 
    66 assert len(_words) == 65536, "lenght is {}".format(len(_words))
    67 
    68 for i, w in enumerate(_words):
    69     print("{l},{i},{w},0".format(l=args.lang[:2], i=i, w=w))