|
| 1 | +import re |
| 2 | +import unicodedata |
| 3 | + |
| 4 | +import regex |
| 5 | + |
| 6 | +# non-ASCII letters that are not separated by "NFKD" normalization |
| 7 | +ADDITIONAL_DIACRITICS = { |
| 8 | + "œ": "oe", |
| 9 | + "Œ": "OE", |
| 10 | + "ø": "o", |
| 11 | + "Ø": "O", |
| 12 | + "æ": "ae", |
| 13 | + "Æ": "AE", |
| 14 | + "ß": "ss", |
| 15 | + "ẞ": "SS", |
| 16 | + "đ": "d", |
| 17 | + "Đ": "D", |
| 18 | + "ð": "d", |
| 19 | + "Ð": "D", |
| 20 | + "þ": "th", |
| 21 | + "Þ": "th", |
| 22 | + "ł": "l", |
| 23 | + "Ł": "L", |
| 24 | +} |
| 25 | + |
| 26 | + |
| 27 | +def remove_symbols_and_diacritics(s: str, keep=""): |
| 28 | + """ |
| 29 | + Replace any other markers, symbols, and punctuations with a space, |
| 30 | + and drop any diacritics (category 'Mn' and some manual mappings) |
| 31 | + """ |
| 32 | + return "".join( |
| 33 | + ( |
| 34 | + c |
| 35 | + if c in keep |
| 36 | + else ( |
| 37 | + ADDITIONAL_DIACRITICS[c] |
| 38 | + if c in ADDITIONAL_DIACRITICS |
| 39 | + else ( |
| 40 | + "" |
| 41 | + if unicodedata.category(c) == "Mn" |
| 42 | + else " " if unicodedata.category(c)[0] in "MSP" else c |
| 43 | + ) |
| 44 | + ) |
| 45 | + ) |
| 46 | + for c in unicodedata.normalize("NFKD", s) |
| 47 | + ) |
| 48 | + |
| 49 | + |
| 50 | +def remove_symbols(s: str): |
| 51 | + """ |
| 52 | + Replace any other markers, symbols, punctuations with a space, keeping diacritics |
| 53 | + """ |
| 54 | + return "".join( |
| 55 | + " " if unicodedata.category(c)[0] in "MSP" else c |
| 56 | + for c in unicodedata.normalize("NFKC", s) |
| 57 | + ) |
| 58 | + |
| 59 | + |
| 60 | +class BasicTextNormalizer: |
| 61 | + def __init__(self, remove_diacritics: bool = False, split_letters: bool = False): |
| 62 | + self.clean = ( |
| 63 | + remove_symbols_and_diacritics if remove_diacritics else remove_symbols |
| 64 | + ) |
| 65 | + self.split_letters = split_letters |
| 66 | + |
| 67 | + def __call__(self, s: str): |
| 68 | + s = s.lower() |
| 69 | + s = re.sub(r"[<\[][^>\]]*[>\]]", "", s) # remove words between brackets |
| 70 | + s = re.sub(r"\(([^)]+?)\)", "", s) # remove words between parenthesis |
| 71 | + s = self.clean(s).lower() |
| 72 | + |
| 73 | + if self.split_letters: |
| 74 | + s = " ".join(regex.findall(r"\X", s, regex.U)) |
| 75 | + |
| 76 | + s = re.sub( |
| 77 | + r"\s+", " ", s |
| 78 | + ) # replace any successive whitespace characters with a space |
| 79 | + |
| 80 | + return s |
0 commit comments