9df2ded02884643002f04e2a01a3c478bf9f6262
[hermes] / package / src / org / maemo / hermes / engine / names.py
1 import trans
2 import re
3
4 """Utilities for determing name variants.
5
6    Copyright (c) Andrew Flegg <andrew@bleb.org> 2009.
7    Released under the Artistic Licence."""
8
9 __non_alpha__ = re.compile("[^A-Za-z]+")
10
11 __names__ = [
12     ['andrew', 'andy', 'andi', 'drew'],
13     ['benjamin', 'ben', 'benny'],
14     ['christian', 'chris'],
15     ['christopher', 'chris'],
16     ['david', 'dave'],
17     ['daniel', 'dan', 'danny'],
18     ['matthew', 'matt', 'mat', 'matty'],
19     ['melanie', 'mel'],
20     ['michael', 'mike', 'mic', 'mik', 'micky'],
21     ['peter', 'pete'],
22     ['robert', 'rob', 'bob', 'bobby', 'robbie'],
23     ['thomas', 'tom', 'tommy']
24   ]
25
26 __map__ = {}
27 for row in __names__:
28     for name in row:
29         if (not name in __map__):
30             __map__[name] = set(row)
31         else:
32             __map__[name] = __map__[name].union(row)
33
34
35 # -----------------------------------------------------------------------
36 def canonical(name, strip = True):
37     """Return a transliterated, lower-case version of name; optionally
38        stripping all non-alphabetic characters from the result."""
39     
40     try:
41         result = unicode(name).encode('trans').lower()
42         if strip:
43             return __non_alpha__.sub('', result)
44         else:
45             return result
46     except UnicodeDecodeError:
47         result = name.lower()
48         if strip:
49             return __non_alpha__.sub('', result)
50         else:
51             return result
52
53 # -----------------------------------------------------------------------
54 def variants(name):
55     """Return a set of names which should be checked for given the input
56        name. Any word which is has a replacement will be replaced, and an
57        iterable list of all variants will be returned."""
58
59     result = set()
60     if (name is None):
61         return result
62     
63     name = canonical(name, strip = False)
64     result.add(name)
65     bits = name.split(' ')
66     for bit in bits:
67         if (bit in __map__):
68             for replacement in __map__[bit]:
69                 result.add(name.replace(bit, replacement))
70
71     return result
72