frhyme.py (1476B)
1 #!/usr/bin/python3 -O 2 3 """Try to guess the last few phonemes of a French word, by a lookup in a 4 precompiled trie""" 5 6 import os 7 import json 8 import sys 9 from pprint import pprint 10 11 DEFAULT_NBEST=5 12 13 f = open(os.path.join(os.path.dirname( 14 os.path.realpath(__file__)), 'frhyme.json')) 15 trie = json.load(f) 16 f.close() 17 18 def to_list(d, rev=True): 19 return [(d[a], a[::-1] if rev else a) for a in d.keys()] 20 21 def trie2list(trie): 22 v, c = trie 23 if c == {}: 24 return to_list(v) 25 else: 26 d = {} 27 for child in c.keys(): 28 l = trie2list(c[child]) 29 for x in l: 30 if x[1] not in d.keys(): 31 d[x[1]] = 0 32 d[x[1]] += x[0] 33 return to_list(d, False) 34 35 def add_dict(a, b): 36 return dict( [ (n, a.get(n, 0)+b.get(n, 0)) for n in set(a)|set(b) ] ) 37 38 def do_lookup(trie, key): 39 if len(key) == 0 or key[0] not in trie[1].keys(): 40 return trie2list(trie) 41 return do_lookup(trie[1][key[0]], key[1:]) 42 43 def nbest(l, t): 44 l = sorted(l)[-t:] 45 l.reverse() 46 return l 47 48 def lookup(key, n=DEFAULT_NBEST): 49 """Return n top pronunciations for key""" 50 return nbest(do_lookup(trie, key[::-1] + ' '), n) 51 52 def wrap_lookup(line, n): 53 pprint(lookup(line.lower().strip(), n)) 54 55 if __name__ == '__main__': 56 n = DEFAULT_NBEST 57 if len(sys.argv) >= 2: 58 n = int(sys.argv[1]) 59 if len(sys.argv) > 2: 60 for arg in sys.argv[2:]: 61 wrap_lookup(arg, n) 62 else: 63 while True: 64 line = sys.stdin.readline() 65 if not line: 66 break 67 wrap_lookup(line, n) 68