forked from zhaowenping/cbeta
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mkdocx.py
1962 lines (1744 loc) · 65.5 KB
/
mkdocx.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 -*-
# Language Version: 2.7+
# Last Modified: 2021-05-14 04:00:41
from __future__ import unicode_literals, division, absolute_import, print_function
"""
函数库
1. 简体繁体检测
2. 简体繁体转换
3. 注音 phonetic notation
4. 注音格式转换
5. 去除'〡'
6. 所有数据装入redis
7. 使用日文30fb,ff65作为标准人名分隔符
"""
__all__ = []
__author__ = ""
__version__ = "0.0.1"
import re
import os
import copy
import gzip
import json
import time
import array
from functools import reduce
from functools import total_ordering
from urllib.parse import quote
import unicodedata
# import xml.dom.minidom as minidom
from xml.etree import ElementTree as ET
import pprint
# docx
import requests
from docx import Document
from docx.shared import Inches, Emu
from docx.shared import Pt
from docx.oxml.ns import qn
from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING
from docx.shared import Pt
from docx.shared import RGBColor
import Levenshtein
print('调用函数库')
PATH = "/home/zhaowp/cbeta/cbeta"
# 拉丁字母0041~024F
def VERTICAL(ctx):
'''竖排标点转横排标点'''
t = { 0xfe10: 0xff0c, # 逗号
0xfe11: 0x3001, # 顿号
0xfe12: 0x3002, # 句号
0xfe13: 0xff1a, # 冒号
0xfe14: 0xff1b, # 分号
0xfe15: 0xff01, # 感叹号
0xfe16: 0xff1f, # 问号
0xfe17: 0x3016, # 左括号
0xfe18: 0x3017, # 右括号
0xfe19: 0x2026, # 省略号
0xfe31: 0x2014, # 破折号
0xfe35: 0xff08, # 左小括号
0xfe36: 0xff09, # 右小括号
0xfe41: 0x300c, # 左内引号
0xfe42: 0x300d, # 右内引号
0xfe43: 0x300e, # 左外引号
0xfe44: 0x300f, # 右外引号
}
# !"#$%&'()*+,-./
# :;<=>?@
# [\]_
# {|}~
ctx = ctx.translate(t)
return ctx
def fullwidth2half(ctx, pun=True, exp=''):
'''全角字符转半角字符, pun: 默认转换全角标点, exp: 不转换的字符列表'''
if pun:
# '!' <= ch <= '~': # 0xFF01~0xFF5E
t = {ch: ch-0xFEE0 for ch in range(0xFF01, 0xFF5F)}
t[0x3000] = 0x20
else:
# if '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z':
t = {ch: ch-0xFEE0 for ch in range(0xFF10, 0xFF1A)}
t.update({ch: ch-0xFEE0 for ch in range(0xFF21, 0xFF3B)})
t.update({ch: ch-0xFEE0 for ch in range(0xFF41, 0xFF5B)})
for ch in exp:
t.pop(ord(ch), None)
ctx = ctx.translate(t)
return ctx
# ctx = array.array('u', ctx)
# SPACE = chr(0x3000)
# if pun:
# for idx, ch in enumerate(ctx):
# if ch == SPACE:
# ctx[idx] = ' '
# elif '!' <= ch <= '~': # 0xFF01~0xFF5E
# ctx[idx] = chr(ord(ch) - 0xFEE0)
# else:
# for idx, ch in enumerate(ctx):
# if '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z':
# ctx[idx] = chr(ord(ch) - 0xFEE0)
# return ctx.tounicode()
def python_unescape(ctx):
'''替换python字样转义字符串为正常汉字'''
for ch in re.findall(r'(?:[^\\]|^)(\\u[a-fA-F0-9]{4})', ctx):
ctx = ctx.replace(ch, chr(int(ch[-4:], 16)))
for ch in re.findall(r'(?:[^\\]|^)(\\U[a-fA-F0-9]{8})', ctx):
ctx = ctx.replace(ch, chr(int(ch[-8:], 16)))
# ctx = ctx.replace(r'\\\\', r'\\')
return ctx
def python_escape(ctx):
'''因为ES不支持F区、G区汉字,所以将F区、G区汉字转换成转义字符序列,方便后续ES中查找'''
for char in ctx:
ordchar = ord(char)
# if 0x2CEB0 <= ordchar <= 0x2EBE0: # F区
# yield r'\U{:08X}'.format(ordchar)
# elif 0x30000 <= ordchar <= 0x3134A: # G区
# yield r'\U{:08X}'.format(ordchar)
if 0x2CEB0 <= ordchar:
yield r'\U{:08X}'.format(ordchar)
else:
yield char
def ids_split(ctx, fn=lambda x:x, exfn=lambda x:x):
'''将字符串按照ids序列分割为数组。遇到ids序列的时候,使用fn处理,返回处理后的数组。'''
stack = []
counter = 0
for ch in ctx:
if counter == 0:
if stack and ch in '↷↹⿰⿱⿴⿵⿶⿷⿸⿹⿺⿻⿲⿳':
yield exfn(''.join(stack))
stack = []
stack.append(ch)
if ch in '↷↹':
counter = 1
elif ch in '⿰⿱⿴⿵⿶⿷⿸⿹⿺⿻':
counter = 2
elif ch in '⿲⿳':
counter = 3
else:
stack.append(ch)
if ch in '↷↹':
pass
elif ch in '⿰⿱⿴⿵⿶⿷⿸⿹⿺⿻':
counter += 1
elif ch in '⿲⿳':
counter += 2
else:
counter -= 1
if counter == 0:
yield fn(''.join(stack))
stack = []
yield exfn(''.join(stack))
def hz_len(ctx):
'''判断一个unicode文本的汉字长度: 有几个汉字组成'''
return sum(ids_split(ctx, fn=lambda x:1, exfn=len))
class IDS:
def __init__(self):
self.ids_dict = dict()
with open('idx/ids.txt') as fd:
for line in fd:
line = line.strip().split()
self.ids_dict[line[2]] = line[1]
self.p = re.compile('|'.join(sorted(self.ids_dict.keys(), key=len, reverse=True)))
def rm_ids(self, ctx):
'''替换unicode ids形式为普通单个字符, 无法替换则保持原样不动'''
# return ''.join(ids_split(ctx, fn=lambda x:self.ids_dict.get(x, x)))
return ''.join(ids_split(ctx, fn=self.find_ids))
def find_ids(self, ctx):
'''查找ids序列
牛 on left = 牜
玉 on left = 𤣩
示 on left = 礻
竹 on top = 𥫗
糸 on left = 糹
肉 on left = 月
艸 on top = 艹
言 on left = 訁
金 on left = 釒
食 on left = 飠
牜𤣩礻糹⺼艹訁釒飠氵冫忄
'''
tt = {'牛': '牜', '王': '𤣩', '示': '礻', '糸': '糹', '月': '⺼',
'草': '艹', '卄': '艹',
'言': '訁',
'金': '釒', '食': '飠', '水': '氵', '冰': '冫', '心': '忄', '人': '亻', '衣': '衤',
'手': '扌', '犬': '犭', '病': '疒', '爪': '爫', '火': '灬', '足': '𧾷'}
rr = self.ids_dict.get(ctx, None)
if rr:
return rr
# TODO re.findall
while True:
x = self.p.findall(ctx)
if not x: break
for i in x:
ctx = ctx.replace(i, self.ids_dict[i])
if not has_ids(ctx):
return ctx
# 没找到就替换之后再找一次
tt = {ord(k): ord(tt[k]) for k in tt}
ctx = ctx.translate(tt) # .replace(chr(0xFFFD), '')
rr = self.ids_dict.get(ctx, None)
if rr:
return rr
return ctx
def has_ids(ctx):
'''判断一个字符串ctx是否包含ids符号'''
for ch in '↷↹⿰⿱⿴⿵⿶⿷⿸⿹⿺⿻⿲⿳':
if ch in ctx:
return True
return False
class CBETA_COM:
def __init__(self):
with open('idx/composition.json') as fd:
self.desc = json.load(fd)
def rm_com(self, ctx):
''' 替换cbeta组字式为相应的字符, 无法替换则替换为空格'''
return ''.join(re_split(r'\[.*?\]', ctx, lambda x: self.desc.get(x, ' ')))
def rm_joiner(ctx):
'''去除汉字的链接和装饰符号: 外圈加方框、圆形或者三角'''
tt = {0x200C:0xFFFD, 0x200D:0xFFFD, 0x20DD:0xFFFD, 0x20DE:0xFFFD, 0x20DF:0xFFFD,
0x20E0:0xFFFD, 0x20E4:0xFFFD, }
ctx = ctx.translate(tt).replace(chr(0xFFFD), '')
return ctx
def rm_ivd(ctx):
'''去除汉字的异体字选择符号, 共256个'''
tt = dict()
for i in range(0xFE00, 0xFE0F+1):
tt[i] = 0xFFFD
for i in range(0xE0100, 0xE01EF+1):
tt[i] = 0xFFFD
ctx = ctx.translate(tt).replace(chr(0xFFFD), '')
return ctx
# _space = re.compile(r'[ \t\n\r\x0b\x0c\u3000]+')
def normalize_space(ctx):
'''去掉字符串两边的空格, 中间连续的多个空格(空白)替换为一个'''
ctx = ctx.strip()
ctx = re.sub(r'\s+', ' ', ctx)
return ctx
def rm_ditto_mark(ctx):
# 在xml中去除四个叠字符号(默认叠字符号始终相连): ⺀ U+2E80 0 /〃 U+3003 2227 /々 U+3005 6415/ 亽 U+4EBD 151/ 𠚤 U+206A4
# 首先删除叠字符号中间的空白
ctx = re.sub(r'([\u3003\u3005\u4ebd\U000206A4])\s+([\u3003\u3005\u4ebd\U000206A4])', r'\1\2', ctx)
ctx = array.array('u', ctx)
dittos = (chr(0x3003), chr(0x3005), chr(0x4ebd), chr(0x206A4))
cc = 0 # 叠字符号的重复次数
len_ctx = len(ctx)
for idx, zi in enumerate(ctx):
if zi in dittos:
cc = cc + 1
if len_ctx > idx+1 and ctx[idx+1] in dittos:
continue
if cc == 0:
continue
j = 0
for i in range(idx-cc, -1, -1):
if ishanzi(ctx[i]):
ctx[idx-j] = ctx[i] # 找到一个合法的重复字符进行替换
j = j + 1
cc = cc - 1
if cc == 0:
break
return ctx.tounicode()
def ishanzi(zi):
'''粗略判断一个字符是否是非叠字汉字'''
zi = ord(zi)
if zi in {'\u2E80', '\u3003', '\u3005', '\u4ebd', '\U000206A4'}:
return False
# 主区和A区, 包括补充区0x4DB6-0x4DBF, 0x9FA6-0x9FFC
if 0x3400 <= zi <= 0x9FFF: # and zi != 0x4EBD:
return True
# BCDEFGH,包括兼容汉字区0x2FXXX
if 0x20000 <= zi <= 0x323BC:
return True
# 〇
if 0x3007 == zi:
return True
# 兼容汉字区
if 0xF900 <= zi <= 0xFAD9:
return True
return False
def unicode_zone(char):
'''汉字编码范围, unicode14.0'''
if 0x4E00 <= ord(char) <= 0x9FA5:
return 'M'
if 0x9FA6 <= ord(char) <= 0x9FFF:
return 'Mx'
if 0x3400 <= ord(char) <= 0x4DB5:
return 'A'
if 0x4DB6 <= ord(char) <= 0x4DBF:
return 'Ax'
if 0x20000 <= ord(char) <= 0x2A6D6:
return 'B'
if 0x2A6D7 <= ord(char) <= 0x2A6DF:
return 'Bx'
if 0x2A700 <= ord(char) <= 0x2B737:
return 'C'
if 0x2B740 <= ord(char) <= 0x2B81D:
return 'D'
if 0x2B820 <= ord(char) <= 0x2CEA1:
return 'E'
if 0x2CEB0 <= ord(char) <= 0x2EBE0:
return 'F'
if 0x30000 <= ord(char) <= 0x3134A:
return 'G'
if 0x31350 <= ord(char) <= 0x323BC:
return 'H'
return ''
def readdb(path, trans=False, reverse=False):
'''读取文本数据库, trans为是否用于tanslate函数, reverse为是否翻转'''
result = dict()
path = os.path.join("/home/zhaowp/cbeta/cbeta", path)
with open(path, encoding='utf8') as fd:
for line in fd:
line = line.strip()
if line.startswith('#') or not line: continue
c0, c1, *cc = line.strip().split()
if trans and reverse:
result[ord(c1)] = ord(c0)
if trans and not reverse:
result[ord(c0)] = ord(c1)
if not trans and reverse:
result[c1] = c0
if not trans and not reverse:
result[c0] = c1
return result
def read_menu_file(sutra_list):
'''读取tab分隔的菜单文件,返回树状字典'''
menu = dict()
print('''读取tab分隔的菜单文件,返回树状字典''')
with open(sutra_list, encoding='utf8') as fd:
for line in fd:
line = line.rstrip()
# if line.startswith('\t\t\t\t\t'):
# print(line)
if not line.startswith('\t'):
key1 = line
menu.update({line:{}})
continue
line = line[1:]
if not line.startswith('\t'):
key2 = line
menu[key1].update({line: {}})
continue
line = line[1:]
if not line.startswith('\t'):
key3 = line
menu[key1][key2].update({line: {}})
continue
line = line[1:]
if not line.startswith('\t'):
key4 = line
menu[key1][key2][key3].update({line: {}})
continue
line = line[1:]
if not line.startswith('\t'):
key5 = line
menu[key1][key2][key3][key4].update({line: {}})
continue
line = line[1:]
if not line.startswith('\t'):
menu[key1][key2][key3][key4][key5].update({line: {}})
continue
return menu
# def ls(pattern):
# result = []
# for path in os.listdir(pattern):
# if path.startswith(sutra) and re.match(pattern, path):
# result.append(path.split('_')[1][:-4])
# return result
def normalize_text(ctx):
'''标准化文本(只适合繁体字)'''
# # 去除上标和下标
# ctx = re.sub(r'\[[\w\*]+\]', '', ctx)
# # 去除组字式
# ctx = rm_com(ctx)
# 去除错误的标点符号
tt = {0xff0e: 0xff65,
0x2027: 0xff65,
0x25CB: ord('〇'), # 佛光山大辞典的用法
}
ctx = ctx.translate(tt)
# 去除两边空格及多余空格
ctx = normalize_space(ctx)
# 去除汉字链接符号
# ctx = rm_joiner(ctx)
# 去除汉字重复符号
ctx = rm_ditto_mark(ctx)
# 去除异体字、异体词
ctx = rm_variant(ctx)
return ctx
def get_first_juan(number):
'''给定经号T01n0002,T20n1113B, T03n0154_002#p0085a13, 返回所有排序后的卷['001', '002', ...]中的第一卷
返回值是一个数字,如果没有找到则返回0'''
if '_' in number:
number = number.split('_')[0]
book, sutra = number.split('n')
# 查找第一卷(有些不是从第一卷开始的)
juan = 999
if not os.path.exists(f'xml/{book}'):
return 0
for path in os.listdir(f'xml/{book}'):
if path.startswith(number):
juan = min(juan, int(path.split('_')[1][:3]))
if juan == 999:
juan = 0
return juan
# lb_anchor 0607a18 #p0481a25
# pb_anchor T02.0125.0603c
@total_ordering
class Number:
'''经号类: T01n0002a_002'''
def __init__(self, n, anchor=''):
if isinstance(n, tuple):
self.book, tome, self.sutra, self.yiyi, self.volume, self.anchor = n
else:
self.book, tome, self.sutra, self.yiyi, self.volume, self.anchor = None, '', '', '', 0, ''
# r = re.findall(r'([A-Z]{1,2})(\d{2,3})n(\w\d{3})([a-zA-Z])?(?:_(\d{3}))?', n)
r = re.findall(r'([A-Z]{1,2})(\d{2,3})n(\w\d{3})([a-zA-Z])?(?:_(\d{3}))?(?:#p(\w\d{3}[abc]\d\d))?', n)
if r:
self.book, tome, self.sutra, self.yiyi, volume, self.anchor = r[0]
self.volume = 0 if not volume else int(volume)
# 重新标准化tome
tome = int(tome)
tome_len = 2
if self.book in {'A', 'C', 'G', 'GA', 'GB', 'L', 'M', 'P', 'U'}:
tome_len = 3
self.tome = f'{tome:0{tome_len}}'
def __eq__(self, other):
return (self.book == other.book and
self.tome == other.tome and
self.sutra == other.sutra and
self.yiyi == other.yiyi and
self.volume == other.volume)
def __lt__(self, other):
'''重要性的排序'''
pr = ("T", "A", "S", "F", "C", "K", "B", "ZW", "P", "U", "D", "G", "M", "N", "L", "J", "X", "Y", "LC", "GA", "GB", "I")
tt = { 'T': 1, 'A': 2, 'F': 3, 'S': 4, 'U': 5,
'P': 6, 'B': 7, 'ZW': 8, 'J': 9, 'C': 10,
'D': 11, 'K': 12, 'G': 13, 'N': 18, 'I':19,
'L': 20, 'M': 30, 'Y':40, 'LC':50,
'GA':60, 'GB': 70, 'ZS':80, 'X':90}
yiyi = 0 if not self.yiyi else int(self.yiyi, 16)
oyiyi = 0 if not other.yiyi else int(other.yiyi, 16)
return (tt[self.book], int(self.tome), int(self.sutra, 16), yiyi, self.volume) < (tt[other.book], int(other.tome), int(other.sutra, 16), oyiyi, other.volume)
def __str__(self):
if not self.book:
return ''
if self.volume:
return f'{self.book}{self.tome}n{self.sutra}{self.yiyi}_{self.volume:03}'
else:
return f'{self.book}{self.tome}n{self.sutra}{self.yiyi}'
@property
def url(self):
if self.volume:
volume = self.volume
else:
volume = self.get_first_juan()
if self.anchor:
return f'/xml/{self.book}{self.tome}/{self.book}{self.tome}n{self.sutra}{self.yiyi}_{volume:03}.xml#{self.anchor}'
else:
return f'/xml/{self.book}{self.tome}/{self.book}{self.tome}n{self.sutra}{self.yiyi}_{volume:03}.xml'
@property
def pages(self):
'''大般若经等....'''
if f'{self.book}{self.sutra}' == 'T0220':
return list(range(1, 601))
number = f'{self.book}{self.tome}n{self.sutra}{self.yiyi}'
if not os.path.exists(f'xml/{self.book}{self.tome}'):
return []
pages = [int(path.split('_')[1][:3]) for path in os.listdir(f'xml/{self.book}{self.tome}') if path.startswith(number)]
return sorted(pages)
def get_first_juan(self):
'''给定经号T01n0002,返回所有排序后的卷['001', '002', ...]中的第一个
返回值是一个数字,如果没有找到则返回0'''
number = f'{self.book}{self.tome}n{self.sutra}{self.yiyi}'
# 查找第一卷(有些不是从第一卷开始的)
juan = 999
if not os.path.exists(f'xml/{self.book}{self.tome}'):
return 0
for path in os.listdir(f'xml/{self.book}{self.tome}'):
if path.startswith(number):
juan = min(juan, int(path.split('_')[1][:3]))
if juan == 999:
juan = 0
return juan
def __add__(self, page):
'''给定经号T01n0002_001,返回T01n0002_002'''
# 重新生成标准经号
if not self.volume:
pass #raise 一个错误?
number = f'{self.book}{self.tome}n{self.sutra}{self.yiyi}_{self.volume:03}'
# # 对所有的book下的卷排序
juanlist = get_sorted_juan(f'{self.book}{self.tome}')
page = juanlist.index(number) + page
if 0 <= page < len(juanlist):
return Number(juanlist[page])
# else: tome + 1
# tomelist: 获得全部book(T01)下的所有排序好的册号列表(T01,T02,T03,T04...)
page = page - len(juanlist)
tomelist = (path.strip(self.book) for path in os.listdir(f'xml') if path.startswith(self.book))
tomelist = tuple(f'{self.book}{i}' for i in sorted(tomelist, key=int))
idx = tomelist.index(f'{self.book}{self.tome}')
if idx + 1 < len(tomelist):
nextbook = tomelist[idx + 1]
juanlist = get_sorted_juan(nextbook)
return Number(juanlist[page])
# else: book + 1
return juanlist
def __sub__(self, page):
'''给定经号T01n0002_002,返回T01n0002_001'''
# 重新生成标准经号
# print('page:', page)
if not self.volume:
pass #raise 一个错误?
number = f'{self.book}{self.tome}n{self.sutra}{self.yiyi}_{self.volume:03}'
# # 对所有的book下的卷排序
juanlist = get_sorted_juan(f'{self.book}{self.tome}')
page = juanlist.index(number) - page
if 0 <= page < len(juanlist):
return Number(juanlist[page])
# else: tome - 1
tomelist = (path.strip(self.book) for path in os.listdir(f'xml') if path.startswith(self.book))
tomelist = [f'{self.book}{i}' for i in sorted(tomelist, key=int)]
idx = tomelist.index(f'{self.book}{self.tome}')
if 0 <= idx - 1:
nextbook = tomelist[idx - 1]
juanlist = get_sorted_juan(nextbook)
return Number(juanlist[page])
# else: book - 1
return juanlist
@property
def title(self):
number = f'{self.book}{self.tome}n{self.sutra}{self.yiyi}'
title = ''
with open("idx/sutra_sch.lst") as fd:
for line in fd:
if number in line:
title = line.strip().split(maxsplit=1)[1]
break
return title
def get_sorted_juan(book):
'''获得book(T01)下的所有排序好的经卷号(T01n0002_001)'''
# 对所有的book下的卷排序
juanlist = []
for path in os.listdir(f'xml/{book}'):
sutra, juan = path[:-4].split('_')
sutra = sutra.split('n')[1]
juanlist.append((sutra, juan))
juanlist.sort(key=lambda x: (int(f'{x[0]:0<5}', 16), int(x[1])))
juanlist = [f'{book}n{i[0]}_{i[1]:0>3}' for i in juanlist]
return juanlist
def grep(filepath, *keyword):
'''对Linux命令grep的模拟,返回一行'''
found = False
with open(filepath) as fd:
for line in fd:
line = line.strip()
if all(kw in line for kw in keyword):
found = True
break
if not found:
return None
return line
sch_db = []
with open(os.path.join(PATH, "idx/sutra_sch.lst")) as fd:
#with open("idx/sutra_sch.lst") as fd:
for line in fd:
line = line.strip().split()[0]
sch_db.append(line)
juan_pattern = re.compile(r'(\s+)第?([\d零〇一二三四五六七八九]{1,4})卷?')
# ../T31/T31n1585.xml#xpath2(//0011b12)
# 雜阿含經一五·一七
# 增一阿含二一·六(大正二·六〇三c) <pb n="0603c" ed="T" xml:id="T02.0125.0603c"/>
ahan_pattern = re.compile(r'(《?[中长長雜杂增][一壹]?阿[含鋡][經经]?》?)第?([\d零〇一二三四五六七八九]{1,4})[經经]')
def parse_ahan(number):
found = False
jinghao = ahan_pattern.findall(number)
if jinghao:
book, sutra = jinghao[0]
sutran = int(sutra)
if '雜' in book or '杂' in book:
book = 'T0099'
if sutran > 1362:
sutran = 1362
if sutran < 1:
sutran = 1
else:
return None
# 查表
with open(f'idx/{book}.xml') as fd:
for line in fd:
line = line.strip().split()
if sutran == int(line[0]):
sutra = Number(line[1])
found = True
break
if not found:
return None
return sutra
# 大正七〇·四五九中、四六〇下
# 大正二、一〇三c
# 大正藏二·四一a
# 大正藏第70卷459页b
# 《大正藏》第40卷第16頁下
# 大正藏第十九卷第16頁下 XXX
pbanchor_pattern = re.compile(r'(《?[中乾佛作傳典刊刻北卍南印叢史品善嘉國圖城外大學宋家寺山師彙志房拓教文新書朝本樂正武永法洪漢片獻珍百石經編纂續脩興華著藏補譯趙遺金隆集順館高麗]+》?)第?(\d{1,3})(?:卷|卷第|\uff65)(\d{1,3})頁?([abcABC])?')
def parse_number2(number):
tt = { ord('〇'): ord('0'), ord('零'): ord('0'),
ord('一'): ord('1'),
ord('二'): ord('2'),
ord('三'): ord('3'),
ord('四'): ord('4'),
ord('五'): ord('5'),
ord('六'): ord('6'),
ord('七'): ord('7'),
ord('八'): ord('8'),
ord('九'): ord('9'),
ord('上'): ord('a'),
ord('中'): ord('b'),
ord('下'): ord('c'),
ord('伍'): ord('5'),
ord('叁'): ord('3'), ord('叄'): ord('3'),
ord('壹'): ord('1'),
ord('捌'): ord('8'),
ord('柒'): ord('7'),
ord('玖'): ord('9'),
ord('肆'): ord('4'),
ord('貳'): ord('2'), ord('贰'): ord('2'),
ord('陆'): ord('6'), ord('陸'): ord('6'),
ord('传'): ord('傳'), ord('丛'): ord('叢'), ord('国'): ord('國'), ord('图'): ord('圖'),
ord('学'): ord('學'), ord('师'): ord('師'), ord('汇'): ord('彙'), ord('书'): ord('書'),
ord('乐'): ord('樂'), ord('汉'): ord('漢'), ord('献'): ord('獻'), ord('经'): ord('經'),
ord('编'): ord('編'), ord('续'): ord('續'), ord('修'): ord('脩'), ord('兴'): ord('興'),
ord('华'): ord('華'), ord('补'): ord('補'), ord('译'): ord('譯'), ord('赵'): ord('趙'),
ord('遗'): ord('遺'), ord('顺'): ord('順'), ord('馆'): ord('館'), ord('丽'): ord('麗'),
ord('页'): ord('頁'), ord('吕'): ord('呂'),
# 伍叁叄壹拾捌柒玖肆貳贰陆陸
# 统一分隔号
0x00b7: 0xff65, 0x2027: 0xff65, 0x30fb: 0xff65, 0xff0e: 0xff65,
}
number = number.translate(tt)
number = re.sub(r'\s+', '', number)
found = False
book = 'T'
anchor = ''
jinghao = pbanchor_pattern.findall(number)
print(number, jinghao)
if jinghao:
book, tome, page, abc = jinghao[0]
page = '{:04}'.format(int(page))
abc = abc.translate(tt).lower()
if '大正' in book:
book = 'T'
if '卍' in book:
book = 'X'
if '高麗' in book:
book = 'K'
if '房山' in book:
book = 'F'
if '印順' in book:
book = 'Y'
if '宋藏' in book:
book = 'S'
if '金' in book:
book = 'A'
if '中華' in book:
book = 'C'
if '嘉興' in book:
book = 'J'
if '永樂北' in book:
book = 'P'
if '洪武南' in book:
book = 'U'
if '圖' in book:
book = 'D'
if '南傳' in book:
book = 'N'
if '藏外' in book:
book = 'ZW'
if '補' in book:
book = 'B'
if '乾隆' in book:
book = 'L'
if '呂澂' in book:
book = 'LC'
if book in {'A', 'C', 'G', 'GA', 'GB', 'L', 'M', 'P', 'U'}:
tome = '{:03}'.format(int(tome))
else:
tome = '{:02}'.format(int(tome))
# 查表
with open('idx/pbidx.txt') as fd:
for line in fd:
line = line.strip()
if f'{book}{tome}' in line and f'{page}{abc}' in line:
number, anchor = line.split()
found = True
if not found:
return None
# url = f'/xml/{book}{tome}/{number}.xml#{anchor}'
# return url
return Number(f'{number}#{anchor}')
# return (book, tome, sutra, j4, volume, anchor)
# 标准模式: T01n0001, T01n0001_001
# 模式1: T01n0001_p0001a01
# 模式2: T01,no.1,p.1a1
# CBETA 2019.Q2, Y25, no. 25, p. 411a5-7
# CBETA, T14, no. 475, pp. 537c8-538a14
# CBETA 2019.Q3, T20, no. 1113B, p. 498c12-17
# CBETA 2019.Q3, A091, no. 1057, pp. 311b03-312a10
# 模式9: '100,3', 't100,3', 100, t1000, t1000_001, 1333b
# TODO: 大宝积经100
jinghaopatten = re.compile(r'([A-Z]{1,2})(\d{2,3})n(\w\d{3})([a-zA-Z])?(?:_(\d{3}))?')
jinghaopatten1 = re.compile(r'([a-zA-Z]{1,2})(\d{2,3})n(\w\d{3})([a-zA-Z])?(?:_(\d{3}))?(?:_p(\w\d{3}[abc]\d\d))?')
jinghaopatten2 = re.compile(r'([a-zA-Z]{1,2})(\d{2,3}),\s*no\.\s*(\w\d{0,3})([a-zA-Z])?,\s*pp?\.\s*(\d+)([abc])(\d+)')
jinghaopatten9 = re.compile(r'([a-zA-Z]{1,2})?(\w\d{0,3})([a-zA-Z])?(?:[\s,._\u3002\uff0c-]+(\d+)?)?') # 全角逗号句号
# jinghaopatten3 = re.compile(r'([\u3007\u3400-\u9FCB\U00020000-\U0002EBE0]+)[ \t,._\u3000\u3002\uff0c-]*(\d+)')
def parse_number1(title, guess_juan=False):
'''所有的anchor都是lb标签的'''
# print(title)
book, tome, sutra, j4, volume, anchor = 'T', '', '', '', '', ''
# book, tome, sutra, j4, volume, anchor
# T, 01, 0001, a 001, p0001a01
found = False
if not found:
jinghao = jinghaopatten1.findall(title)
if jinghao:
book,tome,sutra,j4,volume,anchor = jinghao[0]
found = True
if not found:
jinghao = jinghaopatten2.findall(title)
if jinghao:
book,tome,sutra,j4,anchor,j7,j8 = jinghao[0]
anchor = '{:04}{}{:02}'.format(int(anchor), j7, int(j8))
found = True
if not found:
jinghao = jinghaopatten9.findall(title)
if jinghao:
book,sutra,j4,volume = jinghao[0]
found = True
if title.isdigit():
sutra = '{:04}'.format(int(title))
found = True
if not found:
return None
book = book.upper() if book else 'T'
sutra = sutra.upper().zfill(4)
# TODO: 查找卷数
if not tome:
# 大般若经特例
if volume and f'{book}{sutra}' == 'T0220':
if int(volume) <= 200:
tome = '05'
if 201 <= int(volume) <= 400:
tome = '06'
if int(volume) > 400:
tome = '07'
else:
for line in sch_db:
if book in line and f'n{sutra}' in line:
tome = line.split('n')[0][len(book):]
break
# print(1, '|'.join((title, book,tome,sutra,j4,volume,anchor)))
if not tome:
return None
# 用book,tome,sutra确定j4;有j4确定大小写
found = False
# j4如果是小写就变为大写, 大写就变成小写
j9 = j4.upper() if j4 and ord('a') <= ord(j4) <= ord('z') else j4.lower()
for line in sch_db:
if f'{book}{tome}n{sutra}{j4}' in line:
j4 = line[len(f'{book}{tome}n{sutra}'):]
found = True
break
if f'{book}{tome}n{sutra}{j9}' in line:
j4 = line[len(f'{book}{tome}n{sutra}'):]
found = True
break
if not found:
return None
# 查找第一卷的卷数
if guess_juan and not volume and not anchor:
volume = get_first_juan(f'{book}{tome}n{sutra}{j4}')
# 根据锚来查找卷数volume
if not volume and anchor:
with gzip.open(f'idx/lb/{book}{tome}n{sutra}{j4}.gz', 'rt') as fd:
for line in fd:
if anchor in line:
volume = line.split()[0].split('_')[-1]
break
# print(4, title, book, tome,sutra,j4,volume, anchor)
# 没找到,非法字符串
if guess_juan and not volume:
return None
if volume:
volume = int(volume)
else:
volume = 0
# volume = '{:03}'.format(int(volume))
# ('T', '05', '0220', '', 0, '')
return Number((book, tome, sutra, j4, volume, anchor))
def parse_number(number):
'''尝试解析不同的经号格式'''
sutra = parse_number1(number)
if sutra:
return sutra
# 使用卷册方式查找藏经
sutra = parse_number2(number)
if sutra:
return sutra
# 查找阿含经
sutra = parse_ahan(number)
return sutra
# def normalize_number(number, guess_juan=False):
# '''如果number符合经号的形式, 就标准化为标准形式T01n0001_001, 否则原样返回'''
# result = parse_number1(number, guess_juan)
# if result:
# j1, j2, j3, j4, j5, j6 = result
# if j5:
# number = f'{j1}{j2}n{j3}{j4}_{j5}'
# else:
# number = f'{j1}{j2}n{j3}{j4}'
# return number
#
#
# def make_url(number):
# number = parse_number1(number, True)
# # 如果有锚就添加锚
# if number:
# j1, j2, j3, j4, j5, j6 = number
# else:
# return None
# if j6:
# url = f'xml/{j1}{j2}/{j1}{j2}n{j3}{j4}_{j5}.xml#{j6}'
# else:
# url = f'xml/{j1}{j2}/{j1}{j2}n{j3}{j4}_{j5}.xml'
# return url
# FROM: https://en.wikipedia.org/wiki/International_Alphabet_of_Sanskrit_Transliteration
# FROM: https://en.wikipedia.org/wiki/Harvard-Kyoto
class SA:
'''梵语字符串类, 可以使用HK转写和iast转写输入, 使用天城体, 悉檀体, 拉丁输出'''
pass
def fromlatn(ctx):
vowel = {
'a': chr(0x11580), 'ā': chr(0x11581), 'i': chr(0x11582), 'ī': chr(0x11583),
'u': chr(0x11584), 'ū': chr(0x11585), 'ṛ': chr(0x11586), 'ṝ': chr(0x11587),
'ḷ': chr(0x11588), 'ḹ': chr(0x11589), 'e': chr(0x1158a), 'ai': chr(0x1158b),
'o': chr(0x1158c), 'au': chr(0x1158d),
}
consonant = {
'k': chr(0x1158e), 'kh': chr(0x1158f), 'g': chr(0x11590), 'gh': chr(0x11591),
'ṅ': chr(0x11592), 'c': chr(0x11593), 'ch': chr(0x11594), 'j': chr(0x11595),
'jh': chr(0x11596), 'ñ': chr(0x11597), 'ṭ': chr(0x11598), 'ṭh': chr(0x11599),
'ḍ': chr(0x1159a), 'ḍh': chr(0x1159b), 'ṇ': chr(0x1159c), 't': chr(0x1159d),
'th': chr(0x1159e), 'd': chr(0x1159f), 'dh': chr(0x115a0), 'n': chr(0x115a1),
'p': chr(0x115a2), 'ph': chr(0x115a3), 'b': chr(0x115a4), 'bh': chr(0x115a5),
'm': chr(0x115a6), 'y': chr(0x115a7), 'r': chr(0x115a8), 'l': chr(0x115a9),
'v': chr(0x115aa), 'ś': chr(0x115ab), 'ṣ': chr(0x115ac), 's': chr(0x115ad),
'h': chr(0x115ae),
}
mvowel = {
'ā': chr(0x115af),
'i': chr(0x115b0),
'ī': chr(0x115b1),
'u': chr(0x115b2),
'ū': chr(0x115b3),
'r': chr(0x115b4),
'ṛ': chr(0x115b5),
'e': chr(0x115b8),
'ai': chr(0x115b9),
'o': chr(0x115ba),
'au': chr(0x115bb),
}
sign = {
'ṃ': chr(0x115bd),
'ḥ': chr(0x115be),
}
# '|': chr(0x115c2),
# '||': chr(0x115c3),
def hk2iastdeve(str_in):
'''hk哈佛-京都系统转IAST梵语(天城体)'''
sonorants = {
# Sonorants:
'RR': 'ॠ',
'lR': 'ऌ',
'lRR': 'ॡ ',
}
t1 = {
# Anusvāra and visarg:
'aM': 'अं',
'aH': 'अः',
# Consonants:
'ai': 'ऐ',
'au': 'औ',
'kh': 'ख',
'gh': 'घ',
'ch': 'छ',
'jh': 'झ',
'ph': 'फ',
'Th': 'ठ',
'Dh': 'ढ',
'th': 'थ',
'dh': 'ध',
'bh': 'भ',