/
szu_ed.py
executable file
·222 lines (189 loc) · 7.33 KB
/
szu_ed.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
#!/usr/bin/env python3
#
# Copyright (c) 2014-2015 the Sanzang authors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""Sanzang program module for table editing."""
import getopt
import io
import os
import signal
import sys
import unicodedata
try:
import readline
except ImportError:
pass
USAGE = r"""Usage: szu-ed [options] table_file
Command-line editor for Sanzang translation tables.
Options:
-h, --help print this help message and exit
Mode-setting commands:
\get print the rule for a source term
\set set a translation rule
\rm remove a translation rule
Instant commands:
\p print all translation rules
\w write table to file
\q quit editor
\wq write table and quit
"""
def set_stdio_utf8():
"""
Set standard I/O streams to UTF-8.
Attempt to reassign standard I/O streams to new streams using UTF-8.
Standard input should discard any leading BOM. If an error is raised,
assume the environment is inflexible but correct (IDLE).
"""
try:
sys.stdin = io.TextIOWrapper(
sys.stdin.detach(), encoding='utf-8-sig', line_buffering=True)
sys.stdout = io.TextIOWrapper(
sys.stdout.detach(), encoding='utf-8', line_buffering=True)
sys.stderr = io.TextIOWrapper(
sys.stderr.detach(), encoding='utf-8', line_buffering=True)
except io.UnsupportedOperation:
pass
def read_table(tab_str):
"""
Read a translation table from a formatted string.
Given a translation table as a formatted string, load the contents and
return them as a dictionary. The keys are source terms (column 1),
while each value is a list of the corresponding terms.
"""
tab_str = unicodedata.normalize('NFC', tab_str)
tab = {}
width = -1
for line in tab_str.split('\n'):
rec = [f.strip() for f in line.split('|')]
if width != -1 and width == len(rec):
tab[rec[0]] = rec[1:]
elif width == -1 and len(rec) > 1:
width = len(rec)
tab[rec[0]] = rec[1:]
elif line.strip() != '':
raise RuntimeError('Table error: ' + line.strip())
return tab, width
def table_to_str(tab):
"""
Produce a formatted string for a translation table.
Given a table stored as a dictionary, sort the contents and return the
table as text in the translation table format for storage.
"""
table_str = ''
items = list(tab.items())
items.sort(key=lambda x: (-len(x[0]), x[0]))
for i in items:
table_str += i[0] + '|' + '|'.join(i[1]) + '\n'
return table_str
def edit(table_fpath, input_lines=None):
"""
Open a translation table and run editor commands.
Editor commands are read from standard input by default, and non-error
output is written to standard output. Errors are printed to standard
error. If a list of input lines is also specified, then read editor
input from this list instead of the standard input.
"""
if not os.path.exists(table_fpath):
open(table_fpath, 'w', encoding='utf-8').close()
tab, width = read_table('')
else:
with open(table_fpath, 'r', encoding='utf-8-sig') as fin:
tab, width = read_table(fin.read())
cmd = '\\set'
try:
while True:
if input_lines is None:
line = unicodedata.normalize('NFC', input().strip())
elif len(input_lines) > 0:
line = unicodedata.normalize('NFC', input_lines.pop(0).strip())
else:
return
if line in ('\\get', '\\rm', '\\set'):
cmd = line
elif line == '\\p':
print(table_to_str(tab), end='')
elif line == '\\q':
return
elif line == '\\w' or line == '\\wq':
with open(table_fpath, 'w', encoding='utf-8') as fout:
fout.write(table_to_str(tab))
sys.stderr.write('"%s" (%d lines)\n' % (table_fpath, len(tab)))
if line == '\\wq':
return
elif line != '' and not line.startswith('\\'):
if cmd == '\\get':
try:
print('%s|%s' % (line, '|'.join(tab[line])))
except KeyError:
sys.stderr.write('Not found: ' + line + '\n')
elif cmd == '\\rm':
if line in tab:
old = line + '|' + '|'.join(tab[line])
sys.stderr.write('; --- ' + old + '\n')
del tab[line]
else:
sys.stderr.write('Not found: ' + line + '\n')
elif cmd == '\\set':
toks = [f.strip() for f in line.split('|')]
if width == -1 and len(toks) > 1:
width = len(toks)
if len(toks) == width:
if toks[0] in tab:
old = toks[0] + '|' + '|'.join(tab[toks[0]])
sys.stderr.write('; --- ' + old + '\n')
sys.stderr.write('; +++ ' + '|'.join(toks) + '\n')
tab[toks[0]] = toks[1:]
else:
sys.stderr.write('Invalid assignment: ' + line + '\n')
elif line.strip() == '':
pass
else:
sys.stderr.write('Syntax error: ' + line + '\n')
except EOFError:
return
def main(argv):
"""
Run szu-ed as a portable command-line program.
This program handles data through standard I/O streams as UTF-8 text.
Input has any leading byte-order mark stripped if one is found. Broken
pipes and SIGINT are handled silently.
"""
set_stdio_utf8()
if 'SIGPIPE' in dir(signal):
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
try:
opts, args = getopt.getopt(argv[1:], 'h', ['help'])
for option, _ in opts:
if option in ('-h', '--help'):
print(USAGE, end='')
return 0
if len(args) != 1:
sys.stderr.write(USAGE)
return 1
edit(args[0])
return 0
except getopt.GetoptError:
sys.stderr.write(USAGE)
return 1
except KeyboardInterrupt:
print()
return 1
if __name__ == '__main__':
sys.exit(main(sys.argv))