-
Notifications
You must be signed in to change notification settings - Fork 0
/
crf_wordseg_predict.py
67 lines (54 loc) · 1.73 KB
/
crf_wordseg_predict.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
import glob
import sys
from argparse import ArgumentParser
from typing import List
import pycrfsuite
import crf_wordseg_util
NGRAM = 11
tagger = pycrfsuite.Tagger()
# Tokenize function
def tokenize(text: str) -> List[str]:
text_features = crf_wordseg_util.extract_features(text)
delimiters = tagger.tag(text_features)
tokens = []
token = ""
for i, c in enumerate(text):
if delimiters[i] == "B":
if token:
tokens.append(token)
token = ""
token = token + c
if token:
tokens.append(token)
return tokens
# Execute only if run as a script
# Usage:
# crf-wordseg.py wordseg.model -s "ทดสอบ"
# crf-wordseg.py wordseg.model -f data/nectec-best/TEST_100K.txt
if __name__ == "__main__":
aparser = ArgumentParser(description="Train and segment (tokenize) text")
aparser.add_argument(
"-s", "--segment", nargs=2, metavar=("model_filename", "input_text")
)
aparser.add_argument(
"-ss", "--segmentfile", nargs=2, metavar=("model_filename", "input_filename")
)
args = vars(aparser.parse_args())
if len(sys.argv) < 2:
aparser.print_help()
if args["segment"]:
model_filename = args["segment"][0]
text = args["segment"][1]
tagger.open(model_filename)
tokens = tokenize(text)
print(tokens)
print("|".join(tokens))
if args["segmentfile"]:
model_filename = args["segmentfile"][0]
input_filename = args["segmentfile"][1]
tagger.open(model_filename)
filenames = glob.glob(input_filename)
for filename in filenames:
text = open(filename).read()
tokens = tokenize(text)
print("|".join(tokens))