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