-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
stardict.py
1889 lines (1741 loc) · 60.9 KB
/
stardict.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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim: set ts=4 sw=4 tw=0 et :
#======================================================================
#
# stardict.py -
#
# Created by skywind on 2011/05/13
# Last Modified: 2019/11/09 23:47
#
#======================================================================
from __future__ import print_function
import sys
import time
import os
import io
import csv
import sqlite3
import codecs
try:
import json
except:
import simplejson as json
MySQLdb = None
#----------------------------------------------------------------------
# python3 compatible
#----------------------------------------------------------------------
if sys.version_info[0] >= 3:
unicode = str
long = int
xrange = range
#----------------------------------------------------------------------
# word strip
#----------------------------------------------------------------------
def stripword(word):
return (''.join([ n for n in word if n.isalnum() ])).lower()
#----------------------------------------------------------------------
# StarDict
#----------------------------------------------------------------------
class StarDict (object):
def __init__ (self, filename, verbose = False):
self.__dbname = filename
if filename != ':memory:':
os.path.abspath(filename)
self.__conn = None
self.__verbose = verbose
self.__open()
# 初始化并创建必要的表格和索引
def __open (self):
sql = '''
CREATE TABLE IF NOT EXISTS "stardict" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE,
"word" VARCHAR(64) COLLATE NOCASE NOT NULL UNIQUE,
"sw" VARCHAR(64) COLLATE NOCASE NOT NULL,
"phonetic" VARCHAR(64),
"definition" TEXT,
"translation" TEXT,
"pos" VARCHAR(16),
"collins" INTEGER DEFAULT(0),
"oxford" INTEGER DEFAULT(0),
"tag" VARCHAR(64),
"bnc" INTEGER DEFAULT(NULL),
"frq" INTEGER DEFAULT(NULL),
"exchange" TEXT,
"detail" TEXT,
"audio" TEXT
);
CREATE UNIQUE INDEX IF NOT EXISTS "stardict_1" ON stardict (id);
CREATE UNIQUE INDEX IF NOT EXISTS "stardict_2" ON stardict (word);
CREATE INDEX IF NOT EXISTS "stardict_3" ON stardict (sw, word collate nocase);
CREATE INDEX IF NOT EXISTS "sd_1" ON stardict (word collate nocase);
'''
self.__conn = sqlite3.connect(self.__dbname, isolation_level = "IMMEDIATE")
self.__conn.isolation_level = "IMMEDIATE"
sql = '\n'.join([ n.strip('\t') for n in sql.split('\n') ])
sql = sql.strip('\n')
self.__conn.executescript(sql)
self.__conn.commit()
fields = ( 'id', 'word', 'sw', 'phonetic', 'definition',
'translation', 'pos', 'collins', 'oxford', 'tag', 'bnc', 'frq',
'exchange', 'detail', 'audio' )
self.__fields = tuple([(fields[i], i) for i in range(len(fields))])
self.__names = { }
for k, v in self.__fields:
self.__names[k] = v
self.__enable = self.__fields[3:]
return True
# 数据库记录转化为字典
def __record2obj (self, record):
if record is None:
return None
word = {}
for k, v in self.__fields:
word[k] = record[v]
if word['detail']:
text = word['detail']
try:
obj = json.loads(text)
except:
obj = None
word['detail'] = obj
return word
# 关闭数据库
def close (self):
if self.__conn:
self.__conn.close()
self.__conn = None
def __del__ (self):
self.close()
# 输出日志
def out (self, text):
if self.__verbose:
print(text)
return True
# 查询单词
def query (self, key):
c = self.__conn.cursor()
record = None
if isinstance(key, int) or isinstance(key, long):
c.execute('select * from stardict where id = ?;', (key,))
elif isinstance(key, str) or isinstance(key, unicode):
c.execute('select * from stardict where word = ?', (key,))
else:
return None
record = c.fetchone()
return self.__record2obj(record)
# 查询单词匹配
def match (self, word, limit = 10, strip = False):
c = self.__conn.cursor()
if not strip:
sql = 'select id, word from stardict where word >= ? '
sql += 'order by word collate nocase limit ?;'
c.execute(sql, (word, limit))
else:
sql = 'select id, word from stardict where sw >= ? '
sql += 'order by sw, word collate nocase limit ?;'
c.execute(sql, (stripword(word), limit))
records = c.fetchall()
result = []
for record in records:
result.append(tuple(record))
return result
# 批量查询
def query_batch (self, keys):
sql = 'select * from stardict where '
if keys is None:
return None
if not keys:
return []
querys = []
for key in keys:
if isinstance(key, int) or isinstance(key, long):
querys.append('id = ?')
elif key is not None:
querys.append('word = ?')
sql = sql + ' or '.join(querys) + ';'
query_word = {}
query_id = {}
c = self.__conn.cursor()
c.execute(sql, tuple(keys))
for row in c:
obj = self.__record2obj(row)
query_word[obj['word'].lower()] = obj
query_id[obj['id']] = obj
results = []
for key in keys:
if isinstance(key, int) or isinstance(key, long):
results.append(query_id.get(key, None))
elif key is not None:
results.append(query_word.get(key.lower(), None))
else:
results.append(None)
return tuple(results)
# 取得单词总数
def count (self):
c = self.__conn.cursor()
c.execute('select count(*) from stardict;')
record = c.fetchone()
return record[0]
# 注册新单词
def register (self, word, items, commit = True):
sql = 'INSERT INTO stardict(word, sw) VALUES(?, ?);'
try:
self.__conn.execute(sql, (word, stripword(word)))
except sqlite3.IntegrityError as e:
self.out(str(e))
return False
except sqlite3.Error as e:
self.out(str(e))
return False
self.update(word, items, commit)
return True
# 删除单词
def remove (self, key, commit = True):
if isinstance(key, int) or isinstance(key, long):
sql = 'DELETE FROM stardict WHERE id=?;'
else:
sql = 'DELETE FROM stardict WHERE word=?;'
try:
self.__conn.execute(sql, (key,))
if commit:
self.__conn.commit()
except sqlite3.IntegrityError:
return False
return True
# 清空数据库
def delete_all (self, reset_id = False):
sql1 = 'DELETE FROM stardict;'
sql2 = "UPDATE sqlite_sequence SET seq = 0 WHERE name = 'stardict';"
try:
self.__conn.execute(sql1)
if reset_id:
self.__conn.execute(sql2)
self.__conn.commit()
except sqlite3.IntegrityError as e:
self.out(str(e))
return False
except sqlite3.Error as e:
self.out(str(e))
return False
return True
# 更新单词数据
def update (self, key, items, commit = True):
names = []
values = []
for name, id in self.__enable:
if name in items:
names.append(name)
value = items[name]
if name == 'detail':
if value is not None:
value = json.dumps(value, ensure_ascii = False)
values.append(value)
if len(names) == 0:
if commit:
try:
self.__conn.commit()
except sqlite3.IntegrityError:
return False
return False
sql = 'UPDATE stardict SET ' + ', '.join(['%s=?'%n for n in names])
if isinstance(key, str) or isinstance(key, unicode):
sql += ' WHERE word=?;'
else:
sql += ' WHERE id=?;'
try:
self.__conn.execute(sql, tuple(values + [key]))
if commit:
self.__conn.commit()
except sqlite3.IntegrityError:
return False
return True
# 浏览词典
def __iter__ (self):
c = self.__conn.cursor()
sql = 'select "id", "word" from "stardict"'
sql += ' order by "word" collate nocase;'
c.execute(sql)
return c.__iter__()
# 取得长度
def __len__ (self):
return self.count()
# 检测存在
def __contains__ (self, key):
return self.query(key) is not None
# 查询单词
def __getitem__ (self, key):
return self.query(key)
# 提交变更
def commit (self):
try:
self.__conn.commit()
except sqlite3.IntegrityError:
self.__conn.rollback()
return False
return True
# 取得所有单词
def dumps (self):
return [ n for _, n in self.__iter__() ]
#----------------------------------------------------------------------
# startup MySQLdb
#----------------------------------------------------------------------
def mysql_startup():
global MySQLdb
if MySQLdb is not None:
return True
try:
import MySQLdb as _mysql
MySQLdb = _mysql
except ImportError:
return False
return True
#----------------------------------------------------------------------
# DictMysql
#----------------------------------------------------------------------
class DictMySQL (object):
def __init__ (self, desc, init = False, timeout = 10, verbose = False):
self.__argv = {}
self.__uri = {}
if isinstance(desc, dict):
argv = desc
else:
argv = self.__url_parse(desc)
for k, v in argv.items():
self.__argv[k] = v
if k not in ('engine', 'init', 'db', 'verbose'):
self.__uri[k] = v
self.__uri['connect_timeout'] = timeout
self.__conn = None
self.__verbose = verbose
self.__init = init
if 'db' not in argv:
raise KeyError('not find db name')
self.__open()
def __open (self):
mysql_startup()
if MySQLdb is None:
raise ImportError('No module named MySQLdb')
fields = [ 'id', 'word', 'sw', 'phonetic', 'definition',
'translation', 'pos', 'collins', 'oxford', 'tag', 'bnc', 'frq',
'exchange', 'detail', 'audio' ]
self.__fields = tuple([(fields[i], i) for i in range(len(fields))])
self.__names = { }
for k, v in self.__fields:
self.__names[k] = v
self.__enable = self.__fields[3:]
self.__db = self.__argv.get('db', 'stardict')
if not self.__init:
uri = {}
for k, v in self.__uri.items():
uri[k] = v
uri['db'] = self.__db
self.__conn = MySQLdb.connect(**uri)
else:
self.__conn = MySQLdb.connect(**self.__uri)
return self.init()
return True
# 输出日志
def out (self, text):
if self.__verbose:
print(text)
return True
# 初始化数据库与表格
def init (self):
database = self.__argv.get('db', 'stardict')
self.out('create database: %s'%database)
self.__conn.query("SET sql_notes = 0;")
self.__conn.query('CREATE DATABASE IF NOT EXISTS %s;'%database)
self.__conn.query('USE %s;'%database)
# self.__conn.query('drop table if exists stardict')
sql = '''
CREATE TABLE IF NOT EXISTS `%s`.`stardict` (
`id` INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
`word` VARCHAR(64) NOT NULL UNIQUE KEY,
`sw` VARCHAR(64) NOT NULL,
`phonetic` VARCHAR(64),
`definition` TEXT,
`translation` TEXT,
`pos` VARCHAR(16),
`collins` SMALLINT DEFAULT 0,
`oxford` SMALLINT DEFAULT 0,
`tag` VARCHAR(64),
`bnc` INT DEFAULT NULL,
`frq` INT DEFAULT NULL,
`exchange` TEXT,
`detail` TEXT,
`audio` TEXT,
KEY(`sw`, `word`),
KEY(`collins`),
KEY(`oxford`),
KEY(`tag`)
)
'''%(database)
sql = '\n'.join([ n.strip('\t') for n in sql.split('\n') ])
sql = sql.strip('\n')
sql += ' ENGINE=MyISAM DEFAULT CHARSET=utf8;'
self.__conn.query(sql)
self.__conn.commit()
return True
# 读取 mysql://user:passwd@host:port/database
def __url_parse (self, url):
if url[:8] != 'mysql://':
return None
url = url[8:]
obj = {}
part = url.split('/')
main = part[0]
p1 = main.find('@')
if p1 >= 0:
text = main[:p1].strip()
main = main[p1 + 1:]
p1 = text.find(':')
if p1 >= 0:
obj['user'] = text[:p1].strip()
obj['passwd'] = text[p1 + 1:].strip()
else:
obj['user'] = text
p1 = main.find(':')
if p1 >= 0:
port = main[p1 + 1:]
main = main[:p1]
obj['port'] = int(port)
main = main.strip()
if not main:
main = 'localhost'
obj['host'] = main.strip()
if len(part) >= 2:
obj['db'] = part[1]
return obj
# 数据库记录转化为字典
def __record2obj (self, record):
if record is None:
return None
word = {}
for k, v in self.__fields:
word[k] = record[v]
if word['detail']:
text = word['detail']
try:
obj = json.loads(text)
except:
obj = None
word['detail'] = obj
return word
# 关闭数据库
def close (self):
if self.__conn:
self.__conn.close()
self.__conn = None
def __del__ (self):
self.close()
# 查询单词
def query (self, key):
record = None
if isinstance(key, int) or isinstance(key, long):
sql = 'select * from stardict where id = %s;'
elif isinstance(key, str) or isinstance(key, unicode):
sql = 'select * from stardict where word = %s;'
else:
return None
with self.__conn as c:
c.execute(sql, (key,))
record = c.fetchone()
return self.__record2obj(record)
# 查询单词匹配
def match (self, word, limit = 10, strip = False):
c = self.__conn.cursor()
if not strip:
sql = 'select id, word from stardict where word >= %s '
sql += 'order by word limit %s;'
c.execute(sql, (word, limit))
else:
sql = 'select id, word from stardict where sw >= %s '
sql += 'order by sw, word limit %s;'
c.execute(sql, (stripword(word), limit))
records = c.fetchall()
result = []
for record in records:
result.append(tuple(record))
return result
# 批量查询
def query_batch (self, keys):
sql = 'select * from stardict where '
if keys is None:
return None
if not keys:
return []
querys = []
for key in keys:
if isinstance(key, int) or isinstance(key, long):
querys.append('id = %s')
elif key is not None:
querys.append('word = %s')
sql = sql + ' or '.join(querys) + ';'
query_word = {}
query_id = {}
with self.__conn as c:
c.execute(sql, tuple(keys))
for row in c:
obj = self.__record2obj(row)
query_word[obj['word'].lower()] = obj
query_id[obj['id']] = obj
results = []
for key in keys:
if isinstance(key, int) or isinstance(key, long):
results.append(query_id.get(key, None))
elif key is not None:
results.append(query_word.get(key.lower(), None))
else:
results.append(None)
return tuple(results)
# 注册新单词
def register (self, word, items, commit = True):
sql = 'INSERT INTO stardict(word, sw) VALUES(%s, %s);'
try:
with self.__conn as c:
c.execute(sql, (word, stripword(word)))
except MySQLdb.Error as e:
self.out(str(e))
return False
self.update(word, items, commit)
return True
# 删除单词
def remove (self, key, commit = True):
if isinstance(key, int) or isinstance(key, long):
sql = 'DELETE FROM stardict WHERE id=%s;'
else:
sql = 'DELETE FROM stardict WHERE word=%s;'
try:
with self.__conn as c:
c.execute(sql, (key,))
except MySQLdb.Error as e:
self.out(str(e))
return False
return True
# 清空数据库
def delete_all (self, reset_id = False):
sql1 = 'DELETE FROM stardict;'
try:
with self.__conn as c:
c.execute(sql1)
except MySQLdb.Error as e:
self.out(str(e))
return False
return True
# 更新单词数据
def update (self, key, items, commit = True):
names = []
values = []
for name, id in self.__enable:
if name in items:
names.append(name)
value = items[name]
if name == 'detail':
if value is not None:
value = json.dumps(value, ensure_ascii = False)
values.append(value)
if len(names) == 0:
if commit:
try:
self.__conn.commit()
except MySQLdb.Error as e:
self.out(str(e))
return False
return False
sql = 'UPDATE stardict SET ' + ', '.join(['%s=%%s'%n for n in names])
if isinstance(key, str) or isinstance(key, unicode):
sql += ' WHERE word=%s;'
else:
sql += ' WHERE id=%s;'
try:
with self.__conn as c:
c.execute(sql, tuple(values + [key]))
except MySQLdb.Error as e:
self.out(str(e))
return False
return True
# 取得数据量
def count (self):
sql = 'SELECT count(*) FROM stardict;'
try:
with self.__conn as c:
c.execute(sql)
row = c.fetchone()
return row[0]
except MySQLdb.Error as e:
self.out(str(e))
return -1
return 0
# 提交数据
def commit (self):
try:
self.__conn.commit()
except MySQLdb.Error as e:
self.out(str(e))
return False
return True
# 取得长度
def __len__ (self):
return self.count()
# 检测存在
def __contains__ (self, key):
return self.query(key) is not None
# 查询单词
def __getitem__ (self, key):
return self.query(key)
# 取得所有单词
def dumps (self):
return [ n for _, n in self.__iter__() ]
#----------------------------------------------------------------------
# CSV COLUMNS
#----------------------------------------------------------------------
COLUMN_SIZE = 13
COLUMN_ID = COLUMN_SIZE
COLUMN_SD = COLUMN_SIZE + 1
COLUMN_SW = COLUMN_SIZE + 2
#----------------------------------------------------------------------
# DictCsv
#----------------------------------------------------------------------
class DictCsv (object):
def __init__ (self, filename, codec = 'utf-8'):
self.__csvname = None
if filename is not None:
self.__csvname = os.path.abspath(filename)
self.__codec = codec
self.__heads = ( 'word', 'phonetic', 'definition',
'translation', 'pos', 'collins', 'oxford', 'tag', 'bnc', 'frq',
'exchange', 'detail', 'audio' )
heads = self.__heads
self.__fields = tuple([ (heads[i], i) for i in range(len(heads)) ])
self.__names = {}
for k, v in self.__fields:
self.__names[k] = v
numbers = []
for name in ('collins', 'oxford', 'bnc', 'frq'):
numbers.append(self.__names[name])
self.__numbers = tuple(numbers)
self.__enable = self.__fields[1:]
self.__dirty = False
self.__words = {}
self.__rows = []
self.__index = []
self.__read()
def reset (self):
self.__dirty = False
self.__words = {}
self.__rows = []
self.__index = []
return True
def encode (self, text):
if text is None:
return None
text = text.replace('\\', '\\\\').replace('\n', '\\n')
return text.replace('\r', '\\r')
def decode (self, text):
output = []
i = 0
if text is None:
return None
size = len(text)
while i < size:
c = text[i]
if c == '\\':
c = text[i + 1:i + 2]
if c == '\\':
output.append('\\')
elif c == 'n':
output.append('\n')
elif c == 'r':
output.append('\r')
else:
output.append('\\' + c)
i += 2
else:
output.append(c)
i += 1
return ''.join(output)
# 安全转行整数
def readint (self, text):
if text is None:
return None
if text == '':
return 0
try:
x = long(text)
except:
return 0
if x < 0x7fffffff:
return int(x)
return x
# 读取文件
def __read (self):
self.reset()
filename = self.__csvname
if filename is None:
return False
if not os.path.exists(self.__csvname):
return False
codec = self.__codec
if sys.version_info[0] < 3:
fp = open(filename, 'rb')
content = fp.read()
if not isinstance(content, type(b'')):
content = content.encode(codec, 'ignore')
content = content.replace(b'\r\n', b'\n')
bio = io.BytesIO()
bio.write(content)
bio.seek(0)
reader = csv.reader(bio)
else:
reader = csv.reader(open(filename, encoding = codec))
rows = []
index = []
words = {}
count = 0
for row in reader:
count += 1
if count == 1:
continue
if len(row) < 1:
continue
if sys.version_info[0] < 3:
row = [ n.decode(codec, 'ignore') for n in row ]
if len(row) < COLUMN_SIZE:
row.extend([None] * (COLUMN_SIZE - len(row)))
if len(row) > COLUMN_SIZE:
row = row[:COLUMN_SIZE]
word = row[0].lower()
if word in words:
continue
row.extend([0, 0, stripword(row[0])])
words[word] = 1
rows.append(row)
index.append(row)
self.__rows = rows
self.__index = index
self.__rows.sort(key = lambda row: row[0].lower())
self.__index.sort(key = lambda row: (row[COLUMN_SW], row[0].lower()))
for index in xrange(len(self.__rows)):
row = self.__rows[index]
row[COLUMN_ID] = index
word = row[0].lower()
self.__words[word] = row
for index in xrange(len(self.__index)):
row = self.__index[index]
row[COLUMN_SD] = index
return True
# 保存文件
def save (self, filename = None, codec = 'utf-8'):
if filename is None:
filename = self.__csvname
if filename is None:
return False
if sys.version_info[0] < 3:
fp = open(filename, 'wb')
writer = csv.writer(fp)
else:
fp = open(filename, 'w', encoding = codec, newline = '')
writer = csv.writer(fp)
writer.writerow(self.__heads)
for row in self.__rows:
newrow = []
for n in row:
if isinstance(n, int) or isinstance(n, long):
n = str(n)
elif not isinstance(n, bytes):
if (n is not None) and sys.version_info[0] < 3:
n = n.encode(codec, 'ignore')
newrow.append(n)
writer.writerow(newrow[:COLUMN_SIZE])
fp.close()
return True
# 对象解码
def __obj_decode (self, row):
if row is None:
return None
obj = {}
obj['id'] = row[COLUMN_ID]
obj['sw'] = row[COLUMN_SW]
skip = self.__numbers
for key, index in self.__fields:
value = row[index]
if index in skip:
if value is not None:
value = self.readint(value)
elif key != 'detail':
value = self.decode(value)
obj[key] = value
detail = obj.get('detail', None)
if detail is not None:
if detail != '':
detail = json.loads(detail)
else:
detail = None
obj['detail'] = detail
return obj
# 对象编码
def __obj_encode (self, obj):
row = [ None for i in xrange(len(self.__fields) + 3) ]
for name, idx in self.__fields:
value = obj.get(name, None)
if value is None:
continue
if idx in self.__numbers:
value = str(value)
elif name == 'detail':
value = json.dumps(value, ensure_ascii = False)
else:
value = self.encode(value)
row[idx] = value
return row
# 重新排序
def __resort (self):
self.__rows.sort(key = lambda row: row[0].lower())
self.__index.sort(key = lambda row: (row[COLUMN_SW], row[0].lower()))
for index in xrange(len(self.__rows)):
row = self.__rows[index]
row[COLUMN_ID] = index
for index in xrange(len(self.__index)):
row = self.__index[index]
row[COLUMN_SD] = index
self.__dirty = False
# 查询单词
def query (self, key):
if key is None:
return None
if self.__dirty:
self.__resort()
if isinstance(key, int) or isinstance(key, long):
if key < 0 or key >= len(self.__rows):
return None
return self.__obj_decode(self.__rows[key])
row = self.__words.get(key.lower(), None)
return self.__obj_decode(row)
# 查询单词匹配
def match (self, word, count = 10, strip = False):
if len(self.__rows) == 0:
return []
if self.__dirty:
self.__resort()
if not strip:
index = self.__rows
pos = 0
else:
index = self.__index
pos = COLUMN_SW
top = 0
bottom = len(index) - 1
middle = top
key = word.lower()
if strip:
key = stripword(word)
while top < bottom:
middle = (top + bottom) >> 1
if top == middle or bottom == middle:
break
text = index[middle][pos].lower()
if key == text:
break
elif key < text:
bottom = middle
elif key > text:
top = middle
while index[middle][pos].lower() < key:
middle += 1
if middle >= len(index):
break
cc = COLUMN_ID
likely = [ (tx[cc], tx[0]) for tx in index[middle:middle + count] ]
return likely
# 批量查询
def query_batch (self, keys):
return [ self.query(key) for key in keys ]
# 单词总量
def count (self):
return len(self.__rows)
# 取得长度
def __len__ (self):
return len(self.__rows)
# 取得单词
def __getitem__ (self, key):
return self.query(key)
# 是否存在
def __contains__ (self, key):
return self.__words.__contains__(key.lower())
# 迭代器
def __iter__ (self):
record = []
for index in xrange(len(self.__rows)):
record.append((index, self.__rows[index][0]))
return record.__iter__()
# 注册新单词
def register (self, word, items, commit = True):
if word.lower() in self.__words:
return False
row = self.__obj_encode(items)
row[0] = word
row[COLUMN_ID] = len(self.__rows)
row[COLUMN_SD] = len(self.__rows)
row[COLUMN_SW] = stripword(word)
self.__rows.append(row)
self.__index.append(row)
self.__words[word.lower()] = row
self.__dirty = True
return True
# 删除单词
def remove (self, key, commit = True):
if isinstance(key, int) or isinstance(key, long):
if key < 0 or key >= len(self.__rows):
return False
if self.__dirty:
self.__resort()
key = self.__rows[key][0]
row = self.__words.get(key, None)
if row is None:
return False
if len(self.__rows) == 1:
self.reset()
return True
index = row[COLUMN_ID]
self.__rows[index] = self.__rows[len(self.__rows) - 1]
self.__rows.pop()
index = row[COLUMN_SD]
self.__index[index] = self.__index[len(self.__rows) - 1]
self.__index.pop()
del self.__words[key]
self.__dirty = True
return True
# 清空所有
def delete_all (self, reset_id = False):
self.reset()
return True
# 更改单词
def update (self, key, items, commit = True):
if isinstance(key, int) or isinstance(key, long):