-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtokenizer.py
103 lines (80 loc) · 3.25 KB
/
tokenizer.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import string
import logging
from pprint import pprint, pformat
logging.basicConfig(format="%(levelname)-8s:%(filename)s.%(funcName)20s >> %(message)s")
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
def word_tokenize(s, return_indices=False):
"""
ascii letters -- digits -- punctuations -- whitespace
"""
log.debug('tokenizing:= {} - {}'.format(type(s), s))
tokens = []
indices = []
prev_idx = 0
for i, (c1, c2) in enumerate(zip(s, s[1:])):
#Ascii to others
if c1 in string.ascii_letters and c2 in string.digits:
tokens.append(s[prev_idx:i+1])
indices.append((prev_idx, i+1))
prev_idx = i+1
if c1 in string.ascii_letters and c2 in string.punctuation:
tokens.append(s[prev_idx:i+1])
indices.append((prev_idx, i+1))
prev_idx = i+1
if c1 in string.ascii_letters and c2 in string.whitespace:
tokens.append(s[prev_idx:i+1])
indices.append((prev_idx, i+1))
prev_idx = i+1
#digits to others
if c1 in string.digits and c2 in string.ascii_letters:
tokens.append(s[prev_idx:i+1])
indices.append((prev_idx, i+1))
prev_idx = i+1
if c1 in string.digits and c2 in string.punctuation:
tokens.append(s[prev_idx:i+1])
indices.append((prev_idx, i+1))
prev_idx = i+1
if c1 in string.digits and c2 in string.whitespace:
tokens.append(s[prev_idx:i+1])
indices.append((prev_idx, i+1))
prev_idx = i+1
#whitespace to others
if c1 in string.whitespace and c2 in string.digits:
tokens.append(s[prev_idx:i+1])
indices.append((prev_idx, i+1))
prev_idx = i+1
if c1 in string.whitespace and c2 in string.punctuation:
tokens.append(s[prev_idx:i+1])
indices.append((prev_idx, i+1))
prev_idx = i+1
if c1 in string.whitespace and c2 in string.ascii_letters:
tokens.append(s[prev_idx:i+1])
indices.append((prev_idx, i+1))
prev_idx = i+1
#punctuation to others
if c1 in string.punctuation and c2 in string.punctuation:
tokens.append(s[prev_idx:i+1])
indices.append((prev_idx, i+1))
prev_idx = i+1
if c1 in string.punctuation and c2 in string.digits:
tokens.append(s[prev_idx:i+1])
indices.append((prev_idx, i+1))
prev_idx = i+1
if c1 in string.punctuation and c2 in string.ascii_letters:
tokens.append(s[prev_idx:i+1])
indices.append((prev_idx, i+1))
prev_idx = i+1
if c1 in string.punctuation and c2 in string.whitespace:
tokens.append(s[prev_idx:i+1])
indices.append((prev_idx, i+1))
prev_idx = i+1
else:
tokens.append(s[prev_idx:])
indices.append((prev_idx, len(s)))
if return_indices:
return tokens, indices
return tokens
import sys
if __name__ == '__main__':
print(word_tokenize(sys.argv[1]))