-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
46 lines (35 loc) · 1016 Bytes
/
utils.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
import numpy as np
import pandas as pd
import regex as re
import joblib
import en_core_web_sm
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.svm import LinearSVC
nlp = en_core_web_sm.load()
classifier = LinearSVC()
def clean_text(text):
# reduce multiple spaces and newlines to only one
text = re.sub(r'(\s\s+|\n\n+)', r'\1', text)
# remove double quotes
text = re.sub(r'"', '', text)
return text
def convert_text(text):
sent = nlp(text)
ents = {x.text: x for x in sent.ents}
tokens = []
for w in sent:
if w.is_stop or w.is_punct:
continue
if w.text in ents:
tokens.append(w.text)
else:
tokens.append(w.lemma_.lower())
text = ' '.join(tokens)
return text
class preprocessor(TransformerMixin, BaseEstimator):
def __init__(self):
pass
def fit(self, X, y=None):
return self
def transform(self, X):
return X.apply(clean_text).apply(convert_text)