This repository has been archived by the owner on Feb 4, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 44
/
tokenization.py
102 lines (94 loc) · 2.6 KB
/
tokenization.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
import re
DELIMITERS = '/""\',()?!:;&<>='
INDEL = '/""\',():;&<>='
sentenceMatcher = re.compile(r"(?<!\..)([\?\!\.]+)\s(?!.\.)")
refMatcher = re.compile(r"(\[)\d+(\])")
def isabbrev(s):
abbrev = ['H', 'Hj', 'Ir', 'Jend', 'Purn', 'Prof', 'rer', 'nat', 'Brig', 'Ny', 'Nn', 'Drs', 'Dra', 'dr', 'Ltd', 'Corp', 'Inc']
last = s[:s.find('.')]
return (last in abbrev) or ((len(last)<3) and (last == last.upper()))
def removesubsetstr(strsub,strset):
ls = list(strset)
for c in strsub:
if c in ls: ls.remove(c)
return ''.join(ls)
def cek_inner_delimiter(buf):
if len(buf)>1:
out = []
for cdel in INDEL:
if cdel in buf:
buf = buf.replace(cdel, " "+cdel+" ")
if " " in buf:
return buf.split(" ")
else:
return [buf]
else:
return [buf]
def tokenisasi_kalimat(line):
out = []
tok = line.split(" ")
for t in tok:
buf = t
i = 0
while i<len(buf) and buf[i] in DELIMITERS:
out += [buf[i]]
i += 1
if i < len(t):
buf = buf[i:]
i = -1
akhir = []
while i>=-len(buf) and buf[i] in DELIMITERS:
akhir += [buf[i]]
i -= 1
if -i <= len(buf):
buf = buf[:len(buf)+i+1]
akhir.reverse()
out = out + cek_inner_delimiter(buf) + akhir
if len(out[-1])>1:
buf = out[-1]
i = -1
akhir = []
while i>=-len(buf) and buf[i] in DELIMITERS+'.':
akhir += [buf[i]]
i -= 1
if -i <= len(buf):
buf = buf[:len(buf)+i+1]
if i < -1:
out[-1] = buf
akhir.reverse()
out += akhir
return out
def sentence_extraction(line):
out = []
sent = sentenceMatcher.split(line)
tmp = ''
pre = []
for l in sent:
s = l.strip()
#print s
if len(s)==0: continue
tmp += s.strip()
if (s[-1] in "?!.") or (len(s)==1 and s[0] in "?!."):
pre += [tmp]
tmp = ''
if len(tmp)>0:
pre += [tmp]
tmp = ''
for s in pre:
tmp += s.strip()
if not isabbrev(s[s.rfind(' ')+1:]):
out += [tmp]
tmp = ''
else:
tmp += ' '
if len(tmp)>0:
out += [tmp]
tmp = ''
return out
def cleaning(line):
return refMatcher.sub("", line.strip())
if __name__=='__main__':
l = 'response.content_type . acdef . '
out = sentence_extraction(cleaning(l))
for o in out:
print " ".join(tokenisasi_kalimat(o))