-
Notifications
You must be signed in to change notification settings - Fork 8
/
arabic-preprocess.py
77 lines (58 loc) · 2.48 KB
/
arabic-preprocess.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
import re
import string
import sys
source = sys.argv[1]
output = source+".clean"
# Remove diacritics (Tashkil)
def remove_diacritics(text):
arabic_diacritics = re.compile("""
\u064E | #Fatha
\u064B | #Tanwin Fath
\u0650 | #Kasra
\u064D | #Tanwin Kasr
\u064F | #Damma
\u064C | #Tanwin Damm
\u0652 | #Sukun
\u0651 | #Shadda
\u0640 | #Tatwil/Kashida
""", re.VERBOSE)
text = re.sub(arabic_diacritics, '', text)
return text
# Remove English Characters
def remove_latin(text):
english_characters = re.compile(r'[a-zA-Z]')
text = re.sub(english_characters, '', text)
return text
# Remove the rest of punctuation marks
def remove_punctuation(text):
arabic_punctuations = '''`÷×؛<>_()*&^%][ـ،:"؟.,'{}~¦+|!”…“–ـ/$£•●'''
english_punctuations = string.punctuation
numbers = "1234567890١٢٣٤٥٦٧٨٩٠"
bad_characters = "�¿áóóó□"
punctuations_list = arabic_punctuations + english_punctuations + numbers + bad_characters
replace_slash = str.maketrans('/', ' ', '')
text = text.translate(replace_slash)
remove_punc = str.maketrans('', '', punctuations_list)
text = text.translate(remove_punc)
return text
# Start processing the input file
with open(source) as f:
text = f.read()
# Split on punctuation and remove duplicates
text = re.split(r'\. |\.\n|\!\n|\؟\n|\n', text)
text = list(set(text))
arabic_characters = "اأإبتثجحخدذرزسشصضطظعغفقكلمنهويىة"
with open(output, "w+") as clean:
for segment in text:
segment = segment.strip()
segment = remove_diacritics(segment)
segment = remove_punctuation(segment)
segment = remove_latin(segment)
segment = segment.strip()
segment = " ".join(segment.split()) # remove extra white-spaces
segment = " ".join(segment.split()[:15]) # trancate to 15 tokens
if segment != "" and len(segment.split())>3: # not empty and > 3 tokens (one is <s>)
segment = "<s> " + segment # adding a start token
if segment[4] in arabic_characters:
clean.write(segment + "\n")
print("Done")