forked from h2oai/driverlessai-recipes
-
Notifications
You must be signed in to change notification settings - Fork 1
/
text_meta_transformers.py
72 lines (44 loc) · 2.39 KB
/
text_meta_transformers.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
"""Extract common meta features from text"""
from h2oaicore.transformer_utils import CustomTransformer
import datatable as dt
import numpy as np
import string
class WordBaseTransformer:
_testing_can_skip_failure = False # ensure tested as if shouldn't fail
@staticmethod
def get_default_properties():
return dict(col_type="text", min_cols=1, max_cols=1, relative_importance=1)
def fit_transform(self, X: dt.Frame, y: np.array = None):
return self.transform(X)
class CountWordsTransformer(WordBaseTransformer, CustomTransformer):
_unsupervised = True
def transform(self, X: dt.Frame):
return X.to_pandas().astype(str).iloc[:, 0].apply(lambda x: len(x.split()))
class CountUniqueWordsTransformer(WordBaseTransformer, CustomTransformer):
_unsupervised = True
def transform(self, X: dt.Frame):
return X.to_pandas().astype(str).iloc[:, 0].apply(lambda x: len(set(x.split())))
class CountUpperWordsTransformer(WordBaseTransformer, CustomTransformer):
_unsupervised = True
def transform(self, X: dt.Frame):
return X.to_pandas().astype(str).iloc[:, 0].apply(lambda x: len([w for w in x.split() if w.isupper()]))
class CountNumericWordsTransformer(WordBaseTransformer, CustomTransformer):
_unsupervised = True
def transform(self, X: dt.Frame):
return X.to_pandas().astype(str).iloc[:, 0].apply(lambda x: len([w for w in x.split() if w.isnumeric()]))
class CountUpperCharsTransformer(WordBaseTransformer, CustomTransformer):
_unsupervised = True
def transform(self, X: dt.Frame):
return X.to_pandas().astype(str).iloc[:, 0].apply(lambda x: len([c for c in x if c.isupper()]))
class CountNumericCharsTransformer(WordBaseTransformer, CustomTransformer):
_unsupervised = True
def transform(self, X: dt.Frame):
return X.to_pandas().astype(str).iloc[:, 0].apply(lambda x: len([c for c in x if c.isnumeric()]))
class CountPunctCharsTransformer(WordBaseTransformer, CustomTransformer):
_unsupervised = True
def transform(self, X: dt.Frame):
return X.to_pandas().astype(str).iloc[:, 0].apply(lambda x: len([c for c in x if c in string.punctuation]))
class MeanWordLengthTransformer(WordBaseTransformer, CustomTransformer):
_unsupervised = True
def transform(self, X: dt.Frame):
return X.to_pandas().astype(str).iloc[:, 0].apply(lambda x: np.mean([len(w) for w in str(x).split()]))