|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +""" |
| 4 | +Unicode character finder utility: |
| 5 | +find characters based on words in their official names. |
| 6 | +
|
| 7 | +This can be used from the command line, just pass words as arguments. |
| 8 | +
|
| 9 | +Here is the ``main`` function which makes it happen:: |
| 10 | +
|
| 11 | + >>> main('rook') # doctest: +NORMALIZE_WHITESPACE |
| 12 | + U+2656 ♖ WHITE CHESS ROOK |
| 13 | + U+265C ♜ BLACK CHESS ROOK |
| 14 | + (2 matches for 'rook') |
| 15 | + >>> main('rook', 'black') # doctest: +NORMALIZE_WHITESPACE |
| 16 | + U+265C ♜ BLACK CHESS ROOK |
| 17 | + (1 match for 'rook black') |
| 18 | + >>> main('white bishop') # doctest: +NORMALIZE_WHITESPACE |
| 19 | + U+2657 ♗ WHITE CHESS BISHOP |
| 20 | + (1 match for 'white bishop') |
| 21 | + >>> main("jabberwocky's vest") |
| 22 | + (No match for "jabberwocky's vest") |
| 23 | +
|
| 24 | +
|
| 25 | +For exploring words that occur in the character names, there is the |
| 26 | +``word_report`` function:: |
| 27 | +
|
| 28 | + >>> index = UnicodeNameIndex(sample_chars) |
| 29 | + >>> index.word_report() |
| 30 | + 3 SIGN |
| 31 | + 2 A |
| 32 | + 2 EURO |
| 33 | + 2 LATIN |
| 34 | + 2 LETTER |
| 35 | + 1 CAPITAL |
| 36 | + 1 CURRENCY |
| 37 | + 1 DOLLAR |
| 38 | + 1 SMALL |
| 39 | + >>> index = UnicodeNameIndex() |
| 40 | + >>> index.word_report(7) |
| 41 | + 13196 SYLLABLE |
| 42 | + 11735 HANGUL |
| 43 | + 7616 LETTER |
| 44 | + 2232 WITH |
| 45 | + 2180 SIGN |
| 46 | + 2122 SMALL |
| 47 | + 1709 CAPITAL |
| 48 | +
|
| 49 | +Note: character names starting with the string ``'CJK UNIFIED IDEOGRAPH'`` |
| 50 | +are not indexed. Those names are not useful for searching, since the only |
| 51 | +unique part of the name is the codepoint in hexadecimal. |
| 52 | +
|
| 53 | +""" |
| 54 | + |
| 55 | +import sys |
| 56 | +import re |
| 57 | +import unicodedata |
| 58 | +import pickle |
| 59 | +import warnings |
| 60 | + |
| 61 | +RE_WORD = re.compile('\w+') |
| 62 | + |
| 63 | +INDEX_NAME = 'charfinder_index.pickle' |
| 64 | +MINIMUM_SAVE_LEN = 10000 |
| 65 | +CJK_PREFIX = 'CJK UNIFIED IDEOGRAPH' |
| 66 | + |
| 67 | +sample_chars = [ |
| 68 | + '$', # DOLLAR SIGN |
| 69 | + 'A', # LATIN CAPITAL LETTER A |
| 70 | + 'a', # LATIN SMALL LETTER A |
| 71 | + '\u20a0', # EURO-CURRENCY SIGN |
| 72 | + '\u20ac', # EURO SIGN |
| 73 | +] |
| 74 | + |
| 75 | + |
| 76 | +def tokenize(text): |
| 77 | + """return iterable of uppercased words""" |
| 78 | + for match in RE_WORD.finditer(text): |
| 79 | + yield match.group().upper() |
| 80 | + |
| 81 | + |
| 82 | +class UnicodeNameIndex: |
| 83 | + |
| 84 | + def __init__(self, chars=None): |
| 85 | + self.load(chars) |
| 86 | + |
| 87 | + def load(self, chars=None): |
| 88 | + self.index = None |
| 89 | + if chars is None: |
| 90 | + try: |
| 91 | + with open(INDEX_NAME, 'rb') as fp: |
| 92 | + self.index = pickle.load(fp) |
| 93 | + except OSError: |
| 94 | + pass |
| 95 | + if self.index is None: |
| 96 | + self.build_index(chars) |
| 97 | + if len(self.index) > MINIMUM_SAVE_LEN: |
| 98 | + try: |
| 99 | + self.save() |
| 100 | + except OSError as exc: |
| 101 | + warnings.warn('Could not save {!r}: {}' |
| 102 | + .format(INDEX_NAME, exc)) |
| 103 | + |
| 104 | + def save(self): |
| 105 | + with open(INDEX_NAME, 'wb') as fp: |
| 106 | + pickle.dump(self.index, fp) |
| 107 | + |
| 108 | + def build_index(self, chars=None): |
| 109 | + if chars is None: |
| 110 | + chars = (chr(i) for i in range(32, sys.maxunicode)) |
| 111 | + index = {} |
| 112 | + for char in chars: |
| 113 | + try: |
| 114 | + name = unicodedata.name(char) |
| 115 | + except ValueError: |
| 116 | + continue |
| 117 | + if name.startswith(CJK_PREFIX): |
| 118 | + name = CJK_PREFIX |
| 119 | + code = ord(char) |
| 120 | + |
| 121 | + for word in tokenize(name): |
| 122 | + index.setdefault(word, set()).add(code) |
| 123 | + |
| 124 | + self.index = index |
| 125 | + |
| 126 | + def __len__(self): |
| 127 | + return len(self.index) |
| 128 | + |
| 129 | + def word_rank(self, top=None): |
| 130 | + res = [(len(self.index[key]), key) for key in self.index] |
| 131 | + res.sort(key=lambda item: (-item[0], item[1])) |
| 132 | + if top is not None: |
| 133 | + res = res[:top] |
| 134 | + return res |
| 135 | + |
| 136 | + def word_report(self, top=None): |
| 137 | + """ |
| 138 | + Generate report with most frequent words |
| 139 | +
|
| 140 | + >>> index = UnicodeNameIndex() |
| 141 | + >>> index.word_report(7) |
| 142 | + 13196 SYLLABLE |
| 143 | + 11735 HANGUL |
| 144 | + 7616 LETTER |
| 145 | + 2232 WITH |
| 146 | + 2180 SIGN |
| 147 | + 2122 SMALL |
| 148 | + 1709 CAPITAL |
| 149 | + """ |
| 150 | + for postings, key in self.word_rank(top): |
| 151 | + print('{:5} {}'.format(postings, key)) |
| 152 | + |
| 153 | + def find_codes(self, query): |
| 154 | + result_sets = [] |
| 155 | + for word in tokenize(query): |
| 156 | + if word in self.index: |
| 157 | + result_sets.append(self.index[word]) |
| 158 | + else: # shorcut: no such word |
| 159 | + result_sets = [] |
| 160 | + break |
| 161 | + if result_sets: |
| 162 | + result = result_sets[0] |
| 163 | + result.intersection_update(*result_sets[1:]) |
| 164 | + else: |
| 165 | + result = set() |
| 166 | + if len(result) > 0: |
| 167 | + for code in sorted(result): |
| 168 | + yield code |
| 169 | + |
| 170 | + def describe(self, code): |
| 171 | + code_str = 'U+{:04X}'.format(code) |
| 172 | + char = chr(code) |
| 173 | + name = unicodedata.name(char) |
| 174 | + return '{:7}\t{}\t{}'.format(code_str, char, name) |
| 175 | + |
| 176 | + def find_descriptions(self, query): |
| 177 | + for code in self.find_codes(query): |
| 178 | + yield self.describe(code) |
| 179 | + |
| 180 | + |
| 181 | +def main(*args): |
| 182 | + index = UnicodeNameIndex() |
| 183 | + query = ' '.join(args) |
| 184 | + counter = 0 |
| 185 | + for line in index.find_descriptions(query): |
| 186 | + print(line) |
| 187 | + counter += 1 |
| 188 | + if counter == 0: |
| 189 | + msg = 'No match' |
| 190 | + elif counter == 1: |
| 191 | + msg = '1 match' |
| 192 | + else: |
| 193 | + msg = '{} matches'.format(counter) |
| 194 | + print('({} for {!r})'.format(msg, query)) |
| 195 | + |
| 196 | + |
| 197 | +if __name__ == '__main__': |
| 198 | + if len(sys.argv) > 1: |
| 199 | + main(*sys.argv[1:]) |
| 200 | + else: |
| 201 | + print('Usage: {} word1 [word2]...'.format(sys.argv[0])) |
0 commit comments