-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlookup3.py
235 lines (207 loc) · 8.79 KB
/
lookup3.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
223
224
225
226
227
228
229
230
231
232
233
234
235
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2016 Achim Siebert
# License: GPL v3.0
import os
import sys
import argparse
import appdirs
import simplejson as json
class LookUp():
home = ""
dictFileList = []
dictList = []
dictNames = []
defresult = []
verbose = False
findall = False
reverse = False
sortalpha = False
def change_quotes(self):
self.stringToFind = self.stringToFind.replace("’", "'")
self.stringToFind = self.stringToFind.replace("‘", "'")
self.stringToFind = self.stringToFind.replace('”', '"')
self.stringToFind = self.stringToFind.replace('“', '"')
self.stringToFind = self.stringToFind.replace('„', '"')
def __init__(self, stringToFind):
self.stringToFind = stringToFind
self.change_quotes()
configDir = appdirs.user_data_dir('plover', 'plover')
configFile = os.path.join(configDir, "plover.cfg")
if self.dictNames == []:
try:
infile = open(configFile, 'r')
except:
print("No plover.cfg found")
exit(1)
for line in infile:
if line.find('dictionary_file') == 0:
start_of_path = line.find(' = ') + 3
self.dictFileList.append(str(line[start_of_path:-1]))
infile.close()
if self.dictFileList == []:
print("No dictionaries defined")
exit(1)
for dict in self.dictFileList:
self.dictNames.append(dict[dict.rfind("/")+1:-5])
with open(dict, 'r') as fp:
self.dictList.append(json.load(fp))
def markDoubled(self, strokedef, dname):
for x, result in enumerate(self.defresult[:]):
if result[0] == strokedef:
self.defresult[x][4] = [dname, result[1]]
def find(self):
if self.findall:
self.findAll()
else:
self.findexact()
def findexact(self):
self.defresult = []
i = 0
for dict in self.dictList:
newresult = []
for strokedef in dict:
entry = dict[strokedef]
self.markDoubled(strokedef, self.dictNames[i])
if entry == self.stringToFind:
newresult.append([strokedef, entry, self.dictNames[i], "exact match", []])
elif entry.lower() == self.stringToFind.lower():
newresult.append([strokedef, entry, self.dictNames[i], "entry", []])
elif self.stringToFind + "{^}" == entry:
newresult.append([strokedef, entry, self.dictNames[i], "prefix", []])
elif (self.stringToFind + "{^}{-|}" == entry) or (self.stringToFind + "{-|}" == entry):
newresult.append([strokedef, entry, self.dictNames[i], "capitalize next", []])
elif "{^}" + self.stringToFind == entry:
newresult.append([strokedef, entry, self.dictNames[i], "suffix", []])
elif ("{^}" + self.stringToFind + "{^}" == entry) or \
("{^" + self.stringToFind + "^}" == entry):
newresult.append([strokedef, entry, self.dictNames[i], "infix", []])
self.defresult = self.defresult + newresult
i = i + 1
def findreverse(self):
self.defresult = []
i = 0
for dict in self.dictList:
for strokedef in dict:
entry = dict[strokedef]
self.markDoubled(strokedef, self.dictNames[i])
if strokedef.lower() == self.stringToFind.lower():
self.defresult.append([strokedef, entry, self.dictNames[i], "exact match", []])
elif self.findall and (self.stringToFind.lower() in strokedef.lower()):
self.defresult.append([strokedef, entry, self.dictNames[i], "entry", []])
i = i + 1
def findAll(self):
self.defresult = []
i = 0
for dict in self.dictList:
newresult = []
for strokedef in dict:
entry = dict[strokedef]
self.markDoubled(strokedef, self.dictNames[i])
if self.stringToFind.lower() in entry.lower():
newresult.append([strokedef, entry, self.dictNames[i], "entry", []])
if self.stringToFind == entry:
newresult[-1][3] = "exact match"
if entry.endswith("{^}"):
newresult[-1][3] = "prefix"
if entry.startswith("{^}"):
newresult[-1][3] = "infix"
if entry.startswith("{^}"):
newresult[-1][3] = "suffix"
if entry.startswith("{^") and entry.endswith("^}"):
newresult[-1][3] = "infix"
self.defresult = self.defresult + newresult
i = i + 1
def sortByLength(self):
self.defresult = self.sortByStrokeLength(self.defresult)
self.defresult = self.sortByNumberOfStrokes(self.defresult)
def sortByStrokeLength(self, resultlist):
less = []
equal = []
greater = []
if len(resultlist) > 1:
pivot = len(resultlist[0][0])
for x in resultlist:
if len(x[0]) < pivot:
less.append(x)
if len(x[0]) == pivot:
equal.append(x)
if len(x[0]) > pivot:
greater.append(x)
return self.sortByStrokeLength(less)+equal+self.sortByStrokeLength(greater)
else:
return resultlist
def sortByNumberOfStrokes(self, resultlist):
less = []
equal = []
greater = []
if len(resultlist) > 1:
pivot = resultlist[0][0].count('/')
for x in resultlist:
if x[0].count('/') < pivot:
less.append(x)
if x[0].count('/') == pivot:
equal.append(x)
if x[0].count('/') > pivot:
greater.append(x)
return self.sortByNumberOfStrokes(less)+equal+self.sortByNumberOfStrokes(greater)
else:
return resultlist
def sortAlpha(self):
self.defresult = sorted(self.defresult, key=lambda mydef: mydef[1].lower())
def prettyprint(self):
exactlist = []
restlist = []
if not self.sortalpha:
for item in self.defresult:
if item[3] == "exact match":
exactlist.append(item)
else:
restlist.append(item)
self.defresult = exactlist + restlist
for item in self.defresult:
if item[4] == []:
if self.verbose:
print('{i[0]} – {i[1]} ({i[3]}) – {i[2]}'.format(i=item))
else:
if (item[3] == "exact match") and not self.findall and not self.reverse:
print('{i[0]}'.format(i=item))
else:
print('{i[0]} – {i[1]}'.format(i=item))
else:
if self.verbose:
print('({i[0]} – {i[4][1]} – in {i[2]} overwritten in {i[4][0]})'.format(i=item))
if self.verbose:
print('--- {} result(s) in {} dictionaries ---'.format(len(self.defresult), len(self.dictList)))
def main():
parser = argparse.ArgumentParser(description='Lookup words or strokes in Plover dictionaries')
parser.add_argument('-a', '--all', default=False, action='store_true',
help='list all occurences')
parser.add_argument('-n', '--nosort', default=False, action='store_true',
help='do not sort result by length and number of strokes')
parser.add_argument('-s', '--sortalpha', default=False, action='store_true',
help='sort translations alphabetically')
parser.add_argument('-r', '--reverse', default=False, action='store_true',
help='lookup translation of stroke')
parser.add_argument('-v', '--verbose', default=False, action='store_true',
help='print additional information')
parser.add_argument('words', nargs='+', help='word(s) to look up')
theargs = parser.parse_args()
words = theargs.words
words = " ".join(words)
lkUp = LookUp(words)
lkUp.findall = theargs.all
lkUp.reverse = theargs.reverse
if theargs.reverse:
lkUp.findreverse()
else:
lkUp.find()
if not theargs.nosort and not theargs.sortalpha:
lkUp.sortByLength()
if theargs.sortalpha:
lkUp.sortAlpha()
lkUp.verbose = theargs.verbose
lkUp.sortalpha = theargs.sortalpha
lkUp.prettyprint()
if __name__ == '__main__':
main()