-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPreprocessor.py
74 lines (54 loc) · 2.05 KB
/
Preprocessor.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
import re
import string
class Preprocessor:
def remove_newline(self,sentences,newline = "\n"):
"""
params:
sentences:list of strings
newline: newline character
return: list of strings
remove all new line character from all strings in the list"""
return [sentence.replace(newline,"") for sentence in sentences]
def remove_urls(self,sentences):
"""
params:
sentences:list of strings
return: list of strings
remove all urls character from all strings in the list"""
return [re.sub(r'http\S+', '', sentence) for sentence in sentences]
def remove_digits(self,sentences):
"""
params:
sentences:list of strings
return: list of strings
remove all digits character from all strings in the list"""
return [sentence.translate(str.maketrans('', '', string.digits)).strip() for sentence in sentences]
def remove_punctuations(self,sentences):
"""
params:
sentences:list of strings
return: list of strings
remove all punctuations character from all strings in the list"""
return [sentence.translate(str.maketrans("{}\\“”’".format(string.punctuation), ' '*len("{}\\“”’".format(string.punctuation)), )).strip() for sentence in sentences]
def remove_extreme(self,sentences,n = 2):
"""
params:
sentences:list of strings
n: character number
return: list of strings
remove all strings that have less than n character"""
return [sentence for sentence in sentences if len(sentence)>2]
def preprocess(self,sentences):
"""
params:
sentences:string
return: list of strings
preprocess the emails"""
sentences = sentences.replace("?",".").replace("!",".").split(".") # tokenize string
sentences = self.remove_newline(sentences)
sentences = self.remove_urls(sentences)
sentences = self.remove_digits(sentences)
sentences = self.remove_punctuations(sentences)
sentences = self.remove_extreme(sentences)
sentences = [" ".join(sentence.split()) for sentence in sentences]
return sentences