1def _makeunicodes(f): 2 lines = iter(f.readlines()) 3 unicodes = {} 4 for line in lines: 5 if not line: 6 continue 7 num, name = line.split(";")[:2] 8 if name[0] == "<": 9 continue # "<control>", etc. 10 num = int(num, 16) 11 unicodes[num] = name 12 return unicodes 13 14 15class _UnicodeCustom(object): 16 def __init__(self, f): 17 if isinstance(f, str): 18 with open(f) as fd: 19 codes = _makeunicodes(fd) 20 else: 21 codes = _makeunicodes(f) 22 self.codes = codes 23 24 def __getitem__(self, charCode): 25 try: 26 return self.codes[charCode] 27 except KeyError: 28 return "????" 29 30 31class _UnicodeBuiltin(object): 32 def __getitem__(self, charCode): 33 try: 34 # use unicodedata backport to python2, if available: 35 # https://github.com/mikekap/unicodedata2 36 import unicodedata2 as unicodedata 37 except ImportError: 38 import unicodedata 39 try: 40 return unicodedata.name(chr(charCode)) 41 except ValueError: 42 return "????" 43 44 45Unicode = _UnicodeBuiltin() 46 47 48def setUnicodeData(f): 49 global Unicode 50 Unicode = _UnicodeCustom(f) 51