-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
segment_text.py
77 lines (65 loc) · 1.98 KB
/
segment_text.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
# Copyright (C) 2021 and later: Unicode, Inc. and others.
# License & terms of use: http://www.unicode.org/copyright.html
# Lint as: python3
from lstm_word_segmentation.word_segmenter import pick_lstm_model
import glob, sys, getopt
"""
A sample / simple program to segment the text from standard input
and output the input with segmented result to standout output.
"""
model_name = "Thai_codepoints_exclusive_model4_heavy"
def available_models():
return [ m.replace("Models/", "") \
.replace("/weights.json", "") \
for m in glob.glob("Models/*/weights.json")]
def print_models():
print("Supported Models")
for m in sorted(available_models()):
if m == model_name:
print(" ", m, "[DEFAULT]")
else:
print(" ", m)
def print_usage():
print('segment_text.py -h -l -m model')
print("""
-h \tHelp / Usage
-l \tList models
-m model\tSpecify model
""")
print_models()
def embedding_from_name(name):
if "_codepoints_" in name:
return "codepoints"
else:
return "grapheme_clusters_tf"
def main(argv):
global model_name
try:
opts, args = getopt.getopt(argv,"hlm::")
except getopt.GetoptError:
print_usage()
sys.exit(2)
for opt, arg in opts:
if opt == '-m':
model_name = arg
if opt == '-h':
print_usage()
sys.exit()
if opt == '-l':
print_models()
sys.exit()
file1 = sys.stdin
Lines = file1.readlines()
embedding = embedding_from_name(model_name)
word_segmenter = pick_lstm_model(model_name=model_name, embedding=embedding,
train_data="", eval_data="")
print("Model:", model_name, sep='\t')
print("Embedding:", embedding, sep='\t')
count = 0
# Strips the newline character
for line in Lines:
line = line.strip()
print("Input:", line, sep='\t')
print("Output:", word_segmenter.segment_arbitrary_line(line), sep='\t')
if __name__ == "__main__":
main(sys.argv[1:])