/
textnormalizer.py
228 lines (198 loc) · 6.23 KB
/
textnormalizer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Idea:
https://habr.com/ru/post/86303/
"""
from functools import lru_cache
import re
try: from logHandler import log
except ImportError: import logging as log
@lru_cache(16384)
def normalizer_replace_text(old, new, string, case_insensitive = False):
if case_insensitive:
return string.replace(old, new)
else:
return re.sub(re.escape(old), new, string, flags=re.IGNORECASE)
class TextNormalizer():
"""Translates the letters of the alphabet mixed in normal"""
lang = "?"
Changes = False
IsRu100percent = False
IsEn100percent = False
mixpattern = re.compile(r"\b([а-яё]+[a-z]+[а-яё]+|[a-z]+[а-яё]+[a-z]|[a-z]+[а-яё]|[а-яё]+[a-z])\b",
flags=re.I)
dgpattern = re.compile(
"([0-9]+[k]|mln|mlrd|тыс|"
"(дол|руб|евр|уе|тен|руп|гр?в)[а-я]+|млн|млрд|^[0-9]+(г|кг|т|ц|гц|мгц|"
"мм|см|дм|м|(б|кб|мб|гб|тб)(ит|айт)?)$)",
flags=re.IGNORECASE)
def __init__(self):
self.lettersstrng = {
"α":"а",
"ʍ":"м",
"∂":"д",
"ū":"о",
"ū":"й"
}
self.OnlyRu = "БбвГгДдЁёЖжЗзИиЙйЛлмнПптУФфЦцЧчШшЩщЪъЫыЬьЭэЮюЯя"
self.OnlyEn = "DdFfGghIiJjLlNQqRrSstUVvWwYZz"
self.Rus = "АаВЕеКкМНОоРрСсТуХхЗОтиапьбт"
self.Eng = "AaBEeKkMHOoPpCcTyXx30mu@nb6m"
self.patterns = [
"[kк][аa][kк]",
"[tт][aа][kк]",
r"[a]([\s:,.?!_(){}=+-]+[а-яёА-ЯЁ])",
"[cс][kк][oо][pр][еe][еe]",
"[kк][yу][pр][сc]",
"[kк][yу][pр][сc][eе]",
"[s][kк][yу][pр][eе]",
"[HН][eе][tт]",
"тe",
"eг",
"дe",
"[cс][pр][oо][kк]",
"CCCP",
"CCP",
r"\b[HН][аa]\b",
r"\b[HН][eе]\b",
r"\b[HН][oо]\b",
r"\b[HН][уy]\b",
r"([а-яёА-ЯЁ])m",
r"m([а-яёА-ЯЁ])",
"∂",
"α",
"ū",
"meх",
r"\bom\b",
r"([а-яёА-ЯЁ])pu"
]
self.replaces = [
"как",
"так",
r"а\1",
"скорее",
"курс",
"курсе",
"skype",
"нет",
"те",
"ег",
"де",
"срок",
"СССР",
"ССР",
r"На",
r"Не",
r"Но",
r"Ну",
r"\1т",
r"т\1",
"д",
"а",
"й",
"тех",
"от",
r"\1ри"
]
def CheckWord(self, word, change_case = True):
"""Check the word
Args:
word (str): The source word
Returns:
str: The normalized word
"""
self.Changes = False
self.lang = "?"
# в VK часто стал использоваться символ "ë" как русская буква "е".
newword = normalizer_replace_text("ë", "е", word, True)
# остальные символы из постов VK
for k, v in self.lettersstrng.items():
newword = normalizer_replace_text(k, v, newword, True)
# один символ не имеет смысла
if len(newword.strip()) == 1:
return newword
# Пропускаем хештеги, по скольку там могут быть упоминания через значёк @
if newword[0] == "#":
return newword
# обозначения чисел не меняем
if re.search(self.dgpattern, newword):
return newword
# если есть цифры - не меняем
if re.search("[124579]", newword):
return newword
# если в конце русского слова цифра - не меняем
# если у английского слова цифра три - тоже не меняем
if (re.search("^[а-яёА-ЯЁ]+[0-9]+$", newword)) or (re.search("^[a-zA-Z]+$", newword) and "3" in newword):
return newword
self.IsRu100percent = False
for c1 in word:
for c2 in self.OnlyRu:
self.IsRu100percent = self.IsRu100percent or (c1 == c2)
if self.IsRu100percent:
self.lang = "ru"
for i in range(0, len(self.Rus)):
newword = normalizer_replace_text(self.Eng[i], self.Rus[i], newword, True)
else:
self.IsEn100percent = False
for c1 in word:
for c2 in self.OnlyEn:
self.IsEn100percent = self.IsEn100percent or (c1 == c2)
if self.IsEn100percent:
self.lang = "en"
for i in range(0, len(self.Eng)):
newword = normalizer_replace_text(self.Rus[i], self.Eng[i], newword, True)
# Были ли замены?
self.Changes = newword != word
newword = newword.lower()
if self.Changes and change_case: newword = newword.capitalize()
return newword
def CheckText(self, text, change_case = True):
"""Normalize the text
Args:
text (str): The source text
Returns:
str: The normalized text
"""
# сразу убираем символ "мягкий перенос"
newText = text.replace("\u200d", "").replace(chr(173), "").replace(chr(8205), "")
words = re.findall("[\\w\\@#]+", newText, re.IGNORECASE)
words2 = words.copy()
words2.reverse()
for x in range(0, 3):
words3 = re.findall("[\\w@#]+", newText, flags=re.IGNORECASE)
words4 = [f for f in words3 if re.findall("[a-zA-Z]", f) and re.findall("[а-яА-ЯЁ]", f)]
for word in (words, words2, words4)[x]:
newWord = self.CheckWord(word, change_case)
if self.Changes:
newText = normalizer_replace_text(word, newWord, newText, False)
Rus = ["с", "у", "нет", "ее"]
Eng = ["c", "y", "heт", "ee"]
if text != newText:
newText = newText.replace("B", "В")
newText = newText.replace(" o ", " о ")
newText = newText.replace(" O ", " О ")
newText = newText.replace(" c ", " с ")
newText = newText.replace(" C ", " С ")
for i in range(0, len(Rus)):
newText = normalizer_replace_text(Eng[i], Rus[i], newText, False)
for i in range(0, len(self.patterns)):
if text != newText:
newText = re.sub(self.patterns[i], self.replaces[i], newText, flags=re.IGNORECASE)
newText = re.sub(r"([a-z])у([a-z])", r"\1y\2", newText)
newText = re.sub(r"([a-z])у", r"\1y", newText)
newText = re.sub(r"у([a-z])", r"y\1", newText)
newText = normalizer_replace_text("сh", "ch", newText, True)
newText = normalizer_replace_text("сe", "ce", newText, True)
newText = normalizer_replace_text("Вo", "Bo", newText, True)
return newText
def main():
import sys
args = sys.argv
if len(args) < 2:
print("usage:", args[0], "Need text")
sys.exit()
tn = TextNormalizer()
print(tn.CheckText(args[1]))
if __name__ == "__main__":
main()