-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtext_prep.py
More file actions
49 lines (37 loc) · 1.44 KB
/
Copy pathtext_prep.py
File metadata and controls
49 lines (37 loc) · 1.44 KB
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
import re
import nltk
nltk.download('stopwords')
nltk.download('wordnet')
nltk.download('punkt')
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
def text_prep(X):
documents = []
from nltk.stem import WordNetLemmatizer
from nltk.stem import PorterStemmer
lemmatizer = WordNetLemmatizer()
porter = PorterStemmer()
for sen in range(0, len(X)):
# Remove all the special characters
document = re.sub(r'\W', ' ', str(X[sen]))
# remove all single characters
document = re.sub(r'\s+[a-zA-Z]\s+', ' ', document)
# Remove single characters from the start
document = re.sub(r'\^[a-zA-Z]\s+', ' ', document)
# Substituting multiple spaces with single space
document = re.sub(r'\s+', ' ', document, flags=re.I)
# Removing prefixed 'b'
document = re.sub(r'^b\s+', '', document)
# Converting to Lowercase
document = document.lower()
#remove stopwords
stop_words = set(stopwords.words("english"))
word_tokens = word_tokenize(document)
document = [word for word in word_tokens if not word in stop_words]
document = ' '.join(document)
# Lemmatization
word_tokens = word_tokenize(document)
document = [porter.stem(word) for word in word_tokens]
document = ' '.join(document)
documents.append(document)
return documents