pytextprep-hm25 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pytextprep/__init__.py +36 -0
- pytextprep/cleaner.py +25 -0
- pytextprep/examples/example1_functional.py +9 -0
- pytextprep/examples/example2_pipeline.py +16 -0
- pytextprep/examples/example3_arabic.py +6 -0
- pytextprep/exceptions.py +9 -0
- pytextprep/pipeline.py +79 -0
- pytextprep/registry.py +30 -0
- pytextprep/resources/contractions_en.tsv +55 -0
- pytextprep/resources/stopwords_en.txt +318 -0
- pytextprep/steps/accents.py +22 -0
- pytextprep/steps/cleaning.py +205 -0
- pytextprep/steps/filtering.py +78 -0
- pytextprep/steps/generate_ngrams.py +55 -0
- pytextprep/steps/lemmatizer.py +137 -0
- pytextprep/steps/normalize_arabic.py +47 -0
- pytextprep/steps/slang.py +94 -0
- pytextprep/steps/tokenize.py +39 -0
- pytextprep_hm25-0.1.0.dist-info/METADATA +398 -0
- pytextprep_hm25-0.1.0.dist-info/RECORD +23 -0
- pytextprep_hm25-0.1.0.dist-info/WHEEL +5 -0
- pytextprep_hm25-0.1.0.dist-info/licenses/LICENSE +21 -0
- pytextprep_hm25-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
from pytextprep.registry import requires_str,register_step
|
|
2
|
+
import re
|
|
3
|
+
import html
|
|
4
|
+
import unicodedata
|
|
5
|
+
import string
|
|
6
|
+
|
|
7
|
+
URL_RE=re.compile(r"(?:https?://|www\.)\S+?(?=[.,!?;:)]+(?:\s|$)|\s|$)")
|
|
8
|
+
EMAIL_RE = re.compile(r"[\w.%+-]+@[\w-]+(?:\.[\w-]+)*\.[A-Za-z]{2,}")
|
|
9
|
+
MENTION_RE=re.compile( r'(?<!\w)@[A-Za-z0-9_]+')
|
|
10
|
+
DIGITS_RE=re.compile( r'\d+')
|
|
11
|
+
HASHTAGES_RE=re.compile( r'(?<!\S)#(\S+)')
|
|
12
|
+
EMOJI_RE = re.compile("["
|
|
13
|
+
u"\U0001F600-\U0001F64F" # emoticons
|
|
14
|
+
u"\U0001F300-\U0001F5FF" # symbols & pictographs
|
|
15
|
+
u"\U0001F680-\U0001F6FF" # transport & map symbols
|
|
16
|
+
u"\U0001F1E0-\U0001F1FF" # flags (iOS)
|
|
17
|
+
"]+")
|
|
18
|
+
PUNCTUATION_RE= re.compile(r"""[!"$%&'()*+,\-/:;<=>?\[\]^_`{|}~]|\.(?=\s*$)""")
|
|
19
|
+
HTML_RE = re.compile(r'<.*?>')
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@register_step("lowercase")
|
|
23
|
+
@requires_str
|
|
24
|
+
def lowercase(text:str) ->str:
|
|
25
|
+
"""
|
|
26
|
+
Convert all characters in the text to lowercase.
|
|
27
|
+
|
|
28
|
+
Example:
|
|
29
|
+
lowercase("NLP Rocks") -> "nlp rocks"
|
|
30
|
+
"""
|
|
31
|
+
return text.casefold()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@register_step("normalize_whitespace")
|
|
36
|
+
@requires_str
|
|
37
|
+
def normalize_whitespace(text:str)-> str:
|
|
38
|
+
"""
|
|
39
|
+
Tabs, newlines and repeated spaces become one space; ends stripped.
|
|
40
|
+
Example:
|
|
41
|
+
' a\t\tb\n c ' → 'a b c'
|
|
42
|
+
|
|
43
|
+
"""
|
|
44
|
+
if not text:
|
|
45
|
+
return ""
|
|
46
|
+
return " ".join(text.split())
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@register_step("remove_urls")
|
|
52
|
+
@requires_str
|
|
53
|
+
def remove_urls(text:str, replace_with: str ="") ->str:
|
|
54
|
+
"""
|
|
55
|
+
Remove urls: http://, https:// and www. links; trailing .,!?;:) stays outside the URL
|
|
56
|
+
Example:
|
|
57
|
+
"see www.iti.gov.eg/courses, now" → "see , now"
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
text=URL_RE.sub(replace_with,text)
|
|
61
|
+
return " ".join(text.split())
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@register_step("remove_emails")
|
|
66
|
+
@requires_str
|
|
67
|
+
def remove_emails(text:str, replace_with:str=""):
|
|
68
|
+
"""
|
|
69
|
+
Remove emails form text.
|
|
70
|
+
Example:
|
|
71
|
+
"mail me: a.b@iti.gov.eg" → "mail me:"
|
|
72
|
+
|
|
73
|
+
"""
|
|
74
|
+
text=EMAIL_RE.sub(replace_with,text)
|
|
75
|
+
return " ".join(text.split())
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@register_step("remove_punctuation")
|
|
81
|
+
@requires_str
|
|
82
|
+
def remove_punctuation(text:str, keep_emojis:bool=True)->str:
|
|
83
|
+
"""
|
|
84
|
+
A function to remove Apostrophes,
|
|
85
|
+
replace punctuation or symbol character with space, Emojis survive unless keep_emojis=False
|
|
86
|
+
|
|
87
|
+
Example:
|
|
88
|
+
"stop-words, don't!! 😊" → "stop words dont 😊"
|
|
89
|
+
"""
|
|
90
|
+
if not keep_emojis:
|
|
91
|
+
text=EMOJI_RE .sub("",text)
|
|
92
|
+
if "'" in text:
|
|
93
|
+
text=text.replace("'","")
|
|
94
|
+
for char in string.punctuation:
|
|
95
|
+
text = text.replace(char, " ")
|
|
96
|
+
|
|
97
|
+
return " ".join(text.split())
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@register_step("normalize_repeating_chars")
|
|
102
|
+
@requires_str
|
|
103
|
+
def normalize_repeating_chars(text:str, keep:int=1)->str:
|
|
104
|
+
"""
|
|
105
|
+
Convert a letter repeated 3+ times into keep(1,2,...) copies
|
|
106
|
+
|
|
107
|
+
Example:
|
|
108
|
+
"I looove it, sooo good" → "I love it, so good"
|
|
109
|
+
"""
|
|
110
|
+
|
|
111
|
+
text=re.sub( r'(\w)\1{2,}',r'\1'* keep,text)
|
|
112
|
+
return " ".join(text.split())
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
#Bonus
|
|
119
|
+
|
|
120
|
+
@register_step("remove_mentions")
|
|
121
|
+
@requires_str
|
|
122
|
+
def remove_mentions(text:str)->str:
|
|
123
|
+
"""
|
|
124
|
+
Remove mentions: @user handles, but not emails
|
|
125
|
+
Example:
|
|
126
|
+
"thanks @iti_student!" → "thanks !"
|
|
127
|
+
"""
|
|
128
|
+
|
|
129
|
+
text=MENTION_RE.sub("",text)
|
|
130
|
+
return " ".join(text.split())
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@register_step("remove_digits")
|
|
134
|
+
@requires_str
|
|
135
|
+
def remove_digits(text:str)-> str:
|
|
136
|
+
"""
|
|
137
|
+
Remove digits from text.
|
|
138
|
+
Example:
|
|
139
|
+
"Room 101B" → "Room B"
|
|
140
|
+
"""
|
|
141
|
+
|
|
142
|
+
text=DIGITS_RE.sub("",text)
|
|
143
|
+
return " ".join(text.split())
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
@register_step("remove_hashtags")
|
|
147
|
+
@requires_str
|
|
148
|
+
def remove_hashtags(text:str, keep_word:bool=False)->str:
|
|
149
|
+
"""
|
|
150
|
+
Remove hashtags #tag ; with keep_word=True only the # goes
|
|
151
|
+
Example:
|
|
152
|
+
"#2026 is here" → "is here" or "2026 is here"
|
|
153
|
+
|
|
154
|
+
"""
|
|
155
|
+
if keep_word:
|
|
156
|
+
return text.replace('#',"")
|
|
157
|
+
|
|
158
|
+
text=HASHTAGES_RE.sub("",text)
|
|
159
|
+
return " ".join(text.split())
|
|
160
|
+
|
|
161
|
+
@register_step("remove_html")
|
|
162
|
+
@requires_str
|
|
163
|
+
def remove_html(text:str)->str:
|
|
164
|
+
"""
|
|
165
|
+
Removes HTML tags and decode HTML entities.
|
|
166
|
+
Example:
|
|
167
|
+
"<p>Fish & chips</p>" → "Fish & chips"
|
|
168
|
+
"""
|
|
169
|
+
text=HTML_RE.sub("",text)
|
|
170
|
+
return html.unescape(text)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def is_emoji(char:str)->bool:
|
|
176
|
+
number=ord(char)
|
|
177
|
+
if ( 0x1F300<=number<=0x1FAFF) or ( 0x2600<=number<=0x27BF):
|
|
178
|
+
return True
|
|
179
|
+
return False
|
|
180
|
+
|
|
181
|
+
@register_step("handle_emojis")
|
|
182
|
+
@requires_str
|
|
183
|
+
def handle_emojis(text:str, mode:str="remove")->str:
|
|
184
|
+
"""
|
|
185
|
+
Handle emojis by deleting emojis or replacing each emoji with its Unicode name.
|
|
186
|
+
Example:
|
|
187
|
+
"great 🔥" → "great" or "great :fire:"
|
|
188
|
+
"""
|
|
189
|
+
if mode not in ("remove","text"):
|
|
190
|
+
raise ValueError("mode must be 'remove' or 'text'")
|
|
191
|
+
result=""
|
|
192
|
+
for char in text:
|
|
193
|
+
if char in ("\uFE0F", "\u200D"):
|
|
194
|
+
continue
|
|
195
|
+
if is_emoji(char) and mode=="text":
|
|
196
|
+
result+=" :"+unicodedata.name(char).lower().replace(" ", "_") +":"
|
|
197
|
+
|
|
198
|
+
elif is_emoji(char) and mode=="remove":
|
|
199
|
+
continue
|
|
200
|
+
else:
|
|
201
|
+
result+=char
|
|
202
|
+
|
|
203
|
+
return " ".join(result.split())
|
|
204
|
+
|
|
205
|
+
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
|
|
2
|
+
from pytextprep.registry import register_step,requires_str
|
|
3
|
+
from importlib.resources import files
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
STOPWORDS_FILE = files("pytextprep").joinpath("resources", "stopwords_en.txt")
|
|
7
|
+
|
|
8
|
+
def load_stopwords():
|
|
9
|
+
content=STOPWORDS_FILE.read_text(encoding="utf-8")
|
|
10
|
+
|
|
11
|
+
return content.splitlines()
|
|
12
|
+
|
|
13
|
+
@register_step("remove_stopwords")
|
|
14
|
+
@requires_str
|
|
15
|
+
def remove_stopwords(text:str, custom_words:list[str] | None =None, extra_only:bool=False)->str:
|
|
16
|
+
"""
|
|
17
|
+
Remove stopwords, Uses the built-in English list plus custom_words;
|
|
18
|
+
extra_only=True uses only the custom list. Keeps negations (not, no, nor)
|
|
19
|
+
Example:
|
|
20
|
+
"This is not a good movie" → "not good movie"
|
|
21
|
+
|
|
22
|
+
"""
|
|
23
|
+
custom_words = [word.lower() for word in (custom_words or [])]
|
|
24
|
+
|
|
25
|
+
if extra_only:
|
|
26
|
+
stopwords = custom_words
|
|
27
|
+
else:
|
|
28
|
+
stopwords = [word.lower() for word in load_stopwords()]
|
|
29
|
+
stopwords.extend(custom_words)
|
|
30
|
+
|
|
31
|
+
negations = ["not", "no", "nor"]
|
|
32
|
+
|
|
33
|
+
words = text.split()
|
|
34
|
+
|
|
35
|
+
filtered_words = []
|
|
36
|
+
for word in words:
|
|
37
|
+
if word.lower() not in stopwords:
|
|
38
|
+
filtered_words.append(word)
|
|
39
|
+
elif word.lower() in negations:
|
|
40
|
+
filtered_words.append(word)
|
|
41
|
+
|
|
42
|
+
return " ".join(filtered_words)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
CONTRACTIONS_FILE = files("pytextprep").joinpath("resources", "contractions_en.tsv")
|
|
47
|
+
|
|
48
|
+
def load_contractions():
|
|
49
|
+
content=CONTRACTIONS_FILE.read_text(encoding="utf-8")
|
|
50
|
+
d={}
|
|
51
|
+
for line in content.splitlines():
|
|
52
|
+
key,value=line.split("\t")
|
|
53
|
+
d[key.lower()]=value
|
|
54
|
+
|
|
55
|
+
return d
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@register_step("expand_contractions")
|
|
59
|
+
@requires_str
|
|
60
|
+
def expand_contractions(text:str)->str:
|
|
61
|
+
"""
|
|
62
|
+
Expand the contractions
|
|
63
|
+
Example:
|
|
64
|
+
"Don't worry, I'm here" → "Do not worry, I am here"
|
|
65
|
+
"""
|
|
66
|
+
contractions_dict = load_contractions()
|
|
67
|
+
text = text.replace("’", "'")
|
|
68
|
+
|
|
69
|
+
for word in text.split():
|
|
70
|
+
if word.lower() in contractions_dict:
|
|
71
|
+
if word[0].isupper():
|
|
72
|
+
text = text.replace( word,contractions_dict[word.lower()].capitalize())
|
|
73
|
+
else:
|
|
74
|
+
text = text.replace(word, contractions_dict[word.lower()])
|
|
75
|
+
|
|
76
|
+
return " ".join(text.split())
|
|
77
|
+
|
|
78
|
+
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
|
|
2
|
+
from pytextprep.registry import register_step,requires_str
|
|
3
|
+
@register_step("ngrams")
|
|
4
|
+
def ngrams(tokens:list[str], n:int)->list[str] :
|
|
5
|
+
"""
|
|
6
|
+
Generate consecutive n-grams from a list of token,
|
|
7
|
+
returnS list of word tuples
|
|
8
|
+
Example:
|
|
9
|
+
ngrams(["I","love","NLP"], 2) → [("I","love"), ("love","NLP")]
|
|
10
|
+
|
|
11
|
+
"""
|
|
12
|
+
if not isinstance(tokens, list):
|
|
13
|
+
raise TypeError(f"expected list, got {type(tokens).__name__}")
|
|
14
|
+
for word in tokens:
|
|
15
|
+
if not isinstance(word,str):
|
|
16
|
+
raise ValueError("all words in tokens list must be string")
|
|
17
|
+
if not isinstance(n, int):
|
|
18
|
+
raise TypeError("n must be an integer")
|
|
19
|
+
if n < 1:
|
|
20
|
+
raise ValueError("n must be greater than 0")
|
|
21
|
+
|
|
22
|
+
tokens_ngrams_list=[]
|
|
23
|
+
if n>len(tokens):
|
|
24
|
+
return []
|
|
25
|
+
for i in range(len(tokens)-n+1):
|
|
26
|
+
words_tuples=tuple(tokens[i:i+n])
|
|
27
|
+
tokens_ngrams_list.append(words_tuples)
|
|
28
|
+
return tokens_ngrams_list
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@register_step("char_ngrams")
|
|
33
|
+
@requires_str
|
|
34
|
+
def char_ngrams(word:str, n:int)->list[str]:
|
|
35
|
+
"""
|
|
36
|
+
Generate consecutive character n-grams from a word
|
|
37
|
+
returns list of string, where each string contains n consecutive characters.
|
|
38
|
+
Example:
|
|
39
|
+
char_ngrams("text", 3) → ["tex", "ext"]
|
|
40
|
+
|
|
41
|
+
"""
|
|
42
|
+
if not isinstance(n, int):
|
|
43
|
+
raise TypeError("n must be an integer")
|
|
44
|
+
if n < 1:
|
|
45
|
+
raise ValueError("n must be greater than 0")
|
|
46
|
+
|
|
47
|
+
char_ngram_list=[]
|
|
48
|
+
if n>len(word):
|
|
49
|
+
return []
|
|
50
|
+
for i in range(len(word)-n+1):
|
|
51
|
+
words_dev=word[i:i+n]
|
|
52
|
+
char_ngram_list.append(words_dev)
|
|
53
|
+
return char_ngram_list
|
|
54
|
+
|
|
55
|
+
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
|
|
2
|
+
from pytextprep.registry import requires_str,register_step
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
IRREGULAR_PLURAL_FORMS = {
|
|
6
|
+
|
|
7
|
+
"children": "child",
|
|
8
|
+
"men": "man",
|
|
9
|
+
"women": "woman",
|
|
10
|
+
"feet": "foot",
|
|
11
|
+
"teeth": "tooth",
|
|
12
|
+
"geese": "goose",
|
|
13
|
+
"mice": "mouse",
|
|
14
|
+
"lice": "louse",
|
|
15
|
+
"oxen": "ox",
|
|
16
|
+
"leaves": "leaf",
|
|
17
|
+
"wives": "wife",
|
|
18
|
+
"knives": "knife",
|
|
19
|
+
"wolves": "wolf",
|
|
20
|
+
"lives": "life",
|
|
21
|
+
"shelves": "shelf",
|
|
22
|
+
"thieves": "thief",
|
|
23
|
+
"halves": "half",
|
|
24
|
+
"loaves": "loaf",
|
|
25
|
+
"selves": "self",
|
|
26
|
+
"scarves": "scarf",
|
|
27
|
+
"hooves": "hoof",
|
|
28
|
+
"criteria": "criterion",
|
|
29
|
+
"phenomena": "phenomenon",
|
|
30
|
+
"data": "datum",
|
|
31
|
+
"curricula": "curriculum",
|
|
32
|
+
"memoranda": "memorandum",
|
|
33
|
+
"media": "medium",
|
|
34
|
+
"bacteria": "bacterium",
|
|
35
|
+
"analyses": "analysis",
|
|
36
|
+
"bases": "basis",
|
|
37
|
+
"crises": "crisis",
|
|
38
|
+
"hypotheses": "hypothesis",
|
|
39
|
+
"theses": "thesis",
|
|
40
|
+
"oases": "oasis",
|
|
41
|
+
"diagnoses": "diagnosis",
|
|
42
|
+
"parentheses": "parenthesis",
|
|
43
|
+
"ellipses": "ellipsis",
|
|
44
|
+
"antitheses": "antithesis",
|
|
45
|
+
"synopses": "synopsis",
|
|
46
|
+
"cacti": "cactus",
|
|
47
|
+
"cactuses": "cactus",
|
|
48
|
+
"nuclei": "nucleus",
|
|
49
|
+
"nucleuses": "nucleus",
|
|
50
|
+
"indices": "index",
|
|
51
|
+
"indexes": "index",
|
|
52
|
+
"appendices": "appendix",
|
|
53
|
+
"appendixes": "appendix",
|
|
54
|
+
"fungi": "fungus",
|
|
55
|
+
"funguses": "fungus",
|
|
56
|
+
"genera": "genus",
|
|
57
|
+
"vertebrae": "vertebra",
|
|
58
|
+
"vertices": "vertex",
|
|
59
|
+
"matrixes": "matrix",
|
|
60
|
+
"matrices": "matrix",
|
|
61
|
+
"radii": "radius",
|
|
62
|
+
"stimuli": "stimulus",
|
|
63
|
+
"strata": "stratum",
|
|
64
|
+
"corpora": "corpus",
|
|
65
|
+
"larvae": "larva",
|
|
66
|
+
"syllabi": "syllabus",
|
|
67
|
+
"syllabuses": "syllabus",
|
|
68
|
+
"formulas": "formula",
|
|
69
|
+
"formulae": "formula",
|
|
70
|
+
"memorandums": "memorandum",
|
|
71
|
+
"referenda": "referendum",
|
|
72
|
+
"libretti": "libretto",
|
|
73
|
+
"tableaux": "tableau",
|
|
74
|
+
"tableaus": "tableau",
|
|
75
|
+
"foci": "focus",
|
|
76
|
+
"focusses": "focus",
|
|
77
|
+
"axes": "axis",
|
|
78
|
+
"apices": "apex",
|
|
79
|
+
"apexes": "apex",
|
|
80
|
+
"vortices": "vortex",
|
|
81
|
+
"vortexes": "vortex",
|
|
82
|
+
"codices": "codex",
|
|
83
|
+
"bureaux": "bureau",
|
|
84
|
+
"bureaus": "bureau",
|
|
85
|
+
"chateaux": "chateau",
|
|
86
|
+
"chateaus": "chateau",
|
|
87
|
+
"beaux": "beau",
|
|
88
|
+
"concerti": "concerto",
|
|
89
|
+
"concertos": "concerto",
|
|
90
|
+
"opera": "opus",
|
|
91
|
+
"opuses": "opus",
|
|
92
|
+
"ova": "ovum",
|
|
93
|
+
"phyla": "phylum",
|
|
94
|
+
"fezzes": "fez",
|
|
95
|
+
"quizzes": "quiz",
|
|
96
|
+
"dice": "die",
|
|
97
|
+
"dwarves": "dwarf",
|
|
98
|
+
"dwarfs": "dwarf",
|
|
99
|
+
"fishes": "fish",
|
|
100
|
+
"went": "go",
|
|
101
|
+
"gone": "go",
|
|
102
|
+
"was": "be",
|
|
103
|
+
"were": "be",
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@register_step("lemmatize")
|
|
108
|
+
@requires_str
|
|
109
|
+
def lemmatize(text:str)->str:
|
|
110
|
+
"""
|
|
111
|
+
Rule based lemmatizer returning a word to its base form.
|
|
112
|
+
Handles irregular word forms and common English plural rules.
|
|
113
|
+
|
|
114
|
+
Example:
|
|
115
|
+
"emails studies classes bus" → "email study class bus"
|
|
116
|
+
"""
|
|
117
|
+
words_list = []
|
|
118
|
+
for word in text.split():
|
|
119
|
+
if word in IRREGULAR_PLURAL_FORMS:
|
|
120
|
+
word = IRREGULAR_PLURAL_FORMS[word]
|
|
121
|
+
words_list.append(word)
|
|
122
|
+
continue
|
|
123
|
+
if len(word)>3 and word.endswith("ies"):
|
|
124
|
+
word=word[:-3]+"y"
|
|
125
|
+
elif word.endswith("es") and word[-4:-2] in ['ss','is','us']:
|
|
126
|
+
word=word[:-2]
|
|
127
|
+
elif word.endswith("es") and (word[-4:-2] in ['ch','sh']):
|
|
128
|
+
word=word[:-2]
|
|
129
|
+
elif word.endswith("es") and (word[-3] in ['x','z'] ):
|
|
130
|
+
word=word[:-2]
|
|
131
|
+
elif len(word)>2 and word.endswith("s"):
|
|
132
|
+
if not (word.endswith("is") or word.endswith("ss") or word.endswith("us")):
|
|
133
|
+
word=word[:-1]
|
|
134
|
+
|
|
135
|
+
words_list.append(word)
|
|
136
|
+
return " ".join(words_list)
|
|
137
|
+
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import unicodedata
|
|
2
|
+
from pytextprep.registry import requires_str,register_step
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
# @register_step("normalize_arabic")
|
|
6
|
+
# @requires_str
|
|
7
|
+
# def normalize_arabic(text:str,taa_marbuta: bool = False)->str:
|
|
8
|
+
# """
|
|
9
|
+
# Removes tashkeel and tatweel ة → ه only when taa_marbuta=True
|
|
10
|
+
# Example:
|
|
11
|
+
# "مُحَمَّدٌ" → "محمد", "أحمد" → "احمد", "كبيـــر" → "كبير"
|
|
12
|
+
|
|
13
|
+
# """
|
|
14
|
+
# if taa_marbuta:
|
|
15
|
+
# text=text.replace("ة","ه")
|
|
16
|
+
# text=''.join(c for c in unicodedata.normalize('NFD', text) if unicodedata.category(c) != 'Mn')
|
|
17
|
+
# return text
|
|
18
|
+
|
|
19
|
+
@register_step("normalize_arabic")
|
|
20
|
+
@requires_str
|
|
21
|
+
def normalize_arabic(text:str,taa_marbuta: bool = False)->str:
|
|
22
|
+
"""
|
|
23
|
+
Removes tashkeel and tatweel ة → ه only when taa_marbuta=True
|
|
24
|
+
Example:
|
|
25
|
+
"مُحَمَّدٌ" → "محمد", "أحمد" → "احمد", "كبيـــر" → "كبير"
|
|
26
|
+
|
|
27
|
+
"""
|
|
28
|
+
result = ""
|
|
29
|
+
for char in text:
|
|
30
|
+
number = ord(char)
|
|
31
|
+
|
|
32
|
+
if 0x064B <= number <= 0x0652:
|
|
33
|
+
continue
|
|
34
|
+
elif number == 0x0670 or number == 0x0640:
|
|
35
|
+
continue
|
|
36
|
+
elif char in ["أ", "إ", "آ"]:
|
|
37
|
+
result += "ا"
|
|
38
|
+
elif char == "ى":
|
|
39
|
+
result += "ي"
|
|
40
|
+
elif char == "ة" and taa_marbuta:
|
|
41
|
+
result += "ه"
|
|
42
|
+
else:
|
|
43
|
+
result += char
|
|
44
|
+
|
|
45
|
+
return result
|
|
46
|
+
|
|
47
|
+
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
from pytextprep.registry import requires_str,register_step
|
|
2
|
+
|
|
3
|
+
SLANG_TABLE= {
|
|
4
|
+
"u": "you",
|
|
5
|
+
"r":"are",
|
|
6
|
+
"ur": "your",
|
|
7
|
+
"gr8": "great",
|
|
8
|
+
"bc": "because",
|
|
9
|
+
"brb": "be right back",
|
|
10
|
+
"lol": "laughing out loud",
|
|
11
|
+
"btw": "by the way",
|
|
12
|
+
"omg": "oh my god",
|
|
13
|
+
"idk": "i do not know",
|
|
14
|
+
"tbh": "to be honest",
|
|
15
|
+
"imo": "in my opinion",
|
|
16
|
+
"imho": "in my humble opinion",
|
|
17
|
+
"omw": "on my way",
|
|
18
|
+
"tgif": "thank god it is friday",
|
|
19
|
+
"smh": "shaking my head",
|
|
20
|
+
"jk": "just kidding",
|
|
21
|
+
"fr": "for real",
|
|
22
|
+
"rn": "right now",
|
|
23
|
+
"nvm": "never mind",
|
|
24
|
+
"icymi": "in case you missed it",
|
|
25
|
+
"hmu": "hit me up",
|
|
26
|
+
"tmi": "too much information",
|
|
27
|
+
"cya": "see you",
|
|
28
|
+
"dm": "direct message",
|
|
29
|
+
"ftw": "for the win",
|
|
30
|
+
"fwiw": "for what it is worth",
|
|
31
|
+
"ily": "i love you",
|
|
32
|
+
"irl": "in real life",
|
|
33
|
+
"lmk": "let me know",
|
|
34
|
+
"nbd": "no big deal",
|
|
35
|
+
"np": "no problem",
|
|
36
|
+
"nsfw": "not safe for work",
|
|
37
|
+
"otoh": "on the other hand",
|
|
38
|
+
"rofl": "rolling on the floor laughing",
|
|
39
|
+
"so": "significant other",
|
|
40
|
+
"ttyl": "talk to you later",
|
|
41
|
+
"yolo": "you only live once",
|
|
42
|
+
"idc": "i do not care",
|
|
43
|
+
"lmao": "laughing my ass off",
|
|
44
|
+
"asap": "as soon as possible",
|
|
45
|
+
"bff": "best friends forever",
|
|
46
|
+
"wyd": "what are you doing",
|
|
47
|
+
"wbu": "what about you",
|
|
48
|
+
"ttfn": "ta-ta for now",
|
|
49
|
+
"cu": "see you",
|
|
50
|
+
"iykyk": "if you know, you know",
|
|
51
|
+
"ngl": "not gonna lie",
|
|
52
|
+
"fomo": "fear of missing out",
|
|
53
|
+
"gg": "good game",
|
|
54
|
+
"lfg": "looking for group",
|
|
55
|
+
"op": "overpowered",
|
|
56
|
+
"yas": "yes",
|
|
57
|
+
"yall": "you all",
|
|
58
|
+
"ru": "are you",
|
|
59
|
+
"pls": "please",
|
|
60
|
+
"plz": "please",
|
|
61
|
+
"thx": "thanks",
|
|
62
|
+
"ty": "thank you",
|
|
63
|
+
"gtg": "got to go",
|
|
64
|
+
"tnl": "talk to you later",
|
|
65
|
+
"tmrw": "tomorrow",
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
@register_step("normalize_slang")
|
|
69
|
+
@requires_str
|
|
70
|
+
def normalize_slang(text:str, table:dict[str, str] | None=None)->str:
|
|
71
|
+
"""
|
|
72
|
+
Replaces whole-word slang from a built-in table or the user's own.
|
|
73
|
+
Example:
|
|
74
|
+
"u r gr8" → "you are great"
|
|
75
|
+
|
|
76
|
+
"""
|
|
77
|
+
new_table = SLANG_TABLE.copy()
|
|
78
|
+
if table:
|
|
79
|
+
for key, value in table.items():
|
|
80
|
+
new_table[key.lower()] = value
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
words = text.split()
|
|
84
|
+
for i in range(len(words)):
|
|
85
|
+
clean_word = words[i].lower().strip(".,!?;:")
|
|
86
|
+
|
|
87
|
+
if clean_word in new_table:
|
|
88
|
+
punctuation = ""
|
|
89
|
+
if words[i][-1] in ".,!?;:":
|
|
90
|
+
punctuation = words[i][-1]
|
|
91
|
+
words[i] = new_table[clean_word] + punctuation
|
|
92
|
+
|
|
93
|
+
return " ".join(words)
|
|
94
|
+
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
|
|
2
|
+
from pytextprep.registry import requires_str,register_step
|
|
3
|
+
from typing import List
|
|
4
|
+
import re
|
|
5
|
+
|
|
6
|
+
PUNCTUATION_RE= re.compile(r"""[!"$%&()*+,/:;<=>?\[\]^_`{|}~]|\.(?=\s*$)|(?<!\w)['-]|['-](?!\w)""")
|
|
7
|
+
@register_step("word_tokenize")
|
|
8
|
+
@requires_str
|
|
9
|
+
def word_tokenize(text:str)->list[str]:
|
|
10
|
+
"""
|
|
11
|
+
Splits text into words, keeps internal apostrophes and hyphens, drops punctuation
|
|
12
|
+
Example:
|
|
13
|
+
"State-of-the-art NLP, isn't it?" → ["State-of-the-art", "NLP", "isn't", "it"]
|
|
14
|
+
"""
|
|
15
|
+
if not text:
|
|
16
|
+
return []
|
|
17
|
+
text=PUNCTUATION_RE.sub("",text)
|
|
18
|
+
return text.split()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
ABBREVIATIONS = r"\b(?:Dr|Mr|Mrs|Ms|e\.g|i\.e|etc)\."
|
|
23
|
+
SENTENCE_RE = re.compile(r"(?<=[.!?])\s+(?=[A-Z0-9])")
|
|
24
|
+
@register_step("sent_tokenize")
|
|
25
|
+
@requires_str
|
|
26
|
+
def sent_tokenize(text:str)->list[str]:
|
|
27
|
+
"""
|
|
28
|
+
Splits text into sentences,
|
|
29
|
+
Splits after ., ! or ? followed by a space and a capital letter or digit
|
|
30
|
+
Example:
|
|
31
|
+
"Dr. Ali paid 3.5 EGP. It was cheap!" → ["Dr. Ali paid 3.5 EGP.", "It was cheap!"]
|
|
32
|
+
"""
|
|
33
|
+
if not text:
|
|
34
|
+
return []
|
|
35
|
+
text=re.sub(ABBREVIATIONS,lambda m:m.group().replace(".","<DOT>"),text)
|
|
36
|
+
sentences=SENTENCE_RE.split(text)
|
|
37
|
+
return [s.replace("<DOT>", ".") for s in sentences]
|
|
38
|
+
|
|
39
|
+
|