|
| 1 | +""" |
| 2 | + |
| 3 | +Radical folding and text sanitizing. |
| 4 | + |
| 5 | +Handling a string with `cp1252` symbols: |
| 6 | + >>> order = '"Herr Voß: • 1⁄2 cup of ŒtkerTM caffè latte • bowl of açaí."' |
| 7 | + >>> shave_marks(order) |
| 8 | + '"Herr Voß: • 1⁄2 cup of ŒtkerTM caffe latte • bowl of acai."' |
| 9 | + >>> shave_marks_latin(order) |
| 10 | + '"Herr Voß: • 1⁄2 cup of ŒtkerTM caffe latte • bowl of acai."' |
| 11 | + >>> dewinize(order) |
| 12 | + '"Herr Voß: - 1⁄2 cup of OEtker(TM) caffè latte - bowl of açaí."' |
| 13 | + >>> asciize(order) |
| 14 | + '"Herr Voss: - 1⁄2 cup of OEtker(TM) caffe latte - bowl of acai."' |
| 15 | + |
| 16 | +Handling a string with Greek and Latin accented characters: |
| 17 | + >>> greek = 'Ζέφυρος, Zéfiro' |
| 18 | + >>> shave_marks(greek) |
| 19 | + 'Ζεφυρος, Zefiro' |
| 20 | + >>> shave_marks_latin(greek) |
| 21 | + 'Ζέφυρος, Zefiro' |
| 22 | + >>> dewinize(greek) |
| 23 | + 'Ζέφυρος, Zéfiro' |
| 24 | + >>> asciize(greek) |
| 25 | + 'Ζέφυρος, Zefiro' |
| 26 | + |
| 27 | +""" |
| 28 | + |
| 29 | +import unicodedata |
| 30 | +import string |
| 31 | + |
| 32 | + |
| 33 | +def shave_marks(txt): |
| 34 | + """Remove all diacritic marks""" |
| 35 | + norm_txt = unicodedata.normalize('NFD', txt) |
| 36 | + shaved = ''.join(c for c in norm_txt if not unicodedata.combining(c)) |
| 37 | + return unicodedata.normalize('NFC', shaved) |
| 38 | + |
| 39 | + |
| 40 | +def shave_marks_latin(txt): |
| 41 | + """Remove all diacritic marks from Latin base characters""" |
| 42 | + norm_txt = unicodedata.normalize('NFD', txt) |
| 43 | + latin_base = False |
| 44 | + keepers = [] |
| 45 | + for c in norm_txt: |
| 46 | + if unicodedata.combining(c) and latin_base: |
| 47 | + continue # ignore diacritic on Latin base char |
| 48 | + keepers.append(c) |
| 49 | + # if it isn't combining char, it's a new base char |
| 50 | + if not unicodedata.combining(c): |
| 51 | + latin_base = c in string.ascii_letters |
| 52 | + shaved = ''.join(keepers) |
| 53 | + return unicodedata.normalize('NFC', shaved) |
| 54 | + |
| 55 | + |
| 56 | +single_map = str.maketrans("""‚ƒ„†ˆ‹‘’""•–— ̃›""", |
| 57 | + """'f"*^<''""---~>""") |
| 58 | + |
| 59 | +multi_map = str.maketrans({ # <2> |
| 60 | + '€': '<euro>', |
| 61 | + '...': '...', |
| 62 | + 'Œ': 'OE', |
| 63 | + 'TM': '(TM)', |
| 64 | + 'œ': 'oe', |
| 65 | + '‰': '<per mille>', |
| 66 | + '‡': '**', |
| 67 | +}) |
| 68 | + |
| 69 | +multi_map.update(single_map) |
| 70 | + |
| 71 | + |
| 72 | +def dewinize(txt): |
| 73 | + """Replace Win1252 symbols with ASCII chars or sequences""" |
| 74 | + return txt.translate(multi_map) |
| 75 | + |
| 76 | + |
| 77 | +def asciize(txt): |
| 78 | + no_marks = shave_marks_latin(dewinize(txt)) |
| 79 | + no_marks = no_marks.replace('ß', 'ss') |
| 80 | + return unicodedata.normalize('NFKC', no_marks) |
0 commit comments