-
Notifications
You must be signed in to change notification settings - Fork 2
/
bibmap.py
5635 lines (4679 loc) · 228 KB
/
bibmap.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
"""
A python script to modify bib data and
to display references with specific bibliography standard
two key features:
两大核心功能
1. bib文件抽取,bib文件内容的自定义修改
2. 格式化文献表输出,包括json,bib,text,html,bbl文件,其中bbl文件可以在tex源代码中直接使用,利用natbib、bibmap宏包可以实现不同的标注样式。
"""
__author__ = "Hu zhenzhen"
__version__ = "1.0"
__license__ = "MIT"
__email__ = "[email protected]"
import os
import string
import re
import sys
import datetime
import copy
import json
import operator #数学计算操作符
import argparse #命令行解析
import locale #用locale的方法来进行中文排序,windows下是gbk,一级汉字按拼音排,二级按笔画数排
#引入拼音和笔画顺序的排序数据
import hanzicollationpinyin
import hanzicollationstroke
import hanzipinyindatabase
sqpinyindata=hanzicollationpinyin.sqpinyindata
sqstrokedata=hanzicollationstroke.sqstrokedata
hzpinyindata=hanzipinyindatabase.pinyindatabase
#
#bib数据修改所用的选项数据库
#用于检查用户设置的选项
bibmapoptiondatabase={
'typesource':'entrytype', #对应的值为 entrytype名
'typetarget':'entrytype', #对应的值为 entrytype名
'fieldsource':'entryfield', #对应的值为 entryfield名
'fieldtarget':'entryfield', #对应的值为 entryfield名
'match':'regexp', #对应的值为 regexp(正则表达式)
'notmatch':'regexp', #对应的值为 regexp(正则表达式)
'replace':'regexp', #对应的值为 regexp(正则表达式)
'notfield':'entryfield', #对应的值为 entryfield名
'final':[True,False], #对应的值为 true和false(bool值)
'origfieldval':[True,False], #对应的值为 true, false(bool值)
'append':[True,False], #对应的值为 true, false(bool值)
'appdelim':'string', #添加信息时使用的分隔符,用string(字符串)
'pertype':'entrytype', #对应的值为 entrytype名即条目类型
'pernottype':'entrytype', #对应的值为 entrytype名即条目类型
'fieldset':'entryfield', #对应的值为 entryfield名
'fieldvalue':'string', #对应的值为 string(字符串)
'null':[True,False], #对应的值为 true, false(bool值)
'origfield':[True,False], #对应的值为 true, false(bool值)
'origentrytype':[True,False], #对应的值为 true, false(bool值)
'origfieldval':[True,False], #对应的值为 true, false(bool值)
'overwrite':[True,False],#对应的值为 true, false(bool值)
'fieldfunction':['sethzpinyin','sethzstroke','setsentencecase','settitlecase','settitlecasestd','setuppercase',
'setlowercase','setsmallcaps','setalltitlecase','setauthoran','setdatetoymd'], #对应的值为用户指定的函数名,目前提供的函数主要是:sethzpinyin。
#在域内容处理时,当给出'fieldfunction':'sethzpinyin'选项时,程序会调用sethzpinyin函数以域内容为参数,输出其对应的拼音。'sethzstroke'设置用于排序的笔画顺序字符串。
}
#
#格式化参考文献所用的全局选项数据库
#用于检查用户设置的选项
# 1.若给出的是一个列表,那么设置文档中的选项值应为该列表中的值,否则报错
# 2.若给出的是none那么可以自定义一个列表
formatoptiondatabase={
"style":['numeric','authoryear'],#这个选项目前暂无功能
"nameformat":['uppercase','lowercase','givenahead','familyahead','pinyin','reverseorder'],#姓名处理选项:uppercase,lowercase,given-family,family-given,pinyin
"citenameformat":['titlecase','uppercase'],#标注中的姓名处理选项:uppercase,titlecase
"giveninits":['space','dotspace','dot','terse','false'],#使用名的缩写,space表示名见用空格分隔,dotspace用点加空格,dot用点,terse无分隔,false不使用缩写
"useprefix":[True,False],#使用前缀名
"usesuffix":[True,False],#使用后缀名
"maxbibnames":3,#
"minbibnames":3,#
"maxcitenames":1,#
"mincitenames":1,#
'citecompstart':2, #当连续两个数字就进行压缩
"morenames":[True,False],#
"labelname":"author",#作者年制中作者标签的域的选择设置,比如['author','editor','translator','bookauthor','title'],实际是一个随意设置的列表,这里为了检查机制正常则不设为列表,因为若设为列表,就会检查值是否在database设置的范围内
"labelyear":"year",#作者年制中作者标签的域的选择设置,比如['year','endyear','urlyear']
"labelextrayear":[True,False],#是否使用bibextrayear,citeextrayear来消除姓名列表的歧义
"uniquename":['false','init','true'],#false 不对姓名消除歧义,init则仅使用名的首字母来消除,true则首先使用首字母,不行则使用全名
"uniquelist":['false','minyear','true'],#false 不对姓名消除歧义,minyear则判断时加入labelyear,true不使用year直接对列表消除歧义
"maxbibitems":1,#
"minbibitems":1,#
"moreitems":[True,False],#
"lanorder":'none',#文种排序,指定语言全面的顺序['chinese','japanese','korean','english','french','russian']
'lanfield':'none',#用于指定文献的域列表['author','title'],若第一个域存在则根据其判断,不存在则往后推。
"sorting":'none',#排序,或者指定一个域列表比如['key','author','year','title']
"sortlocale":['none','pinyin','stroke','system'],#本地化排序:'none','pinyin','stroke','system',none不使用,system是操作系统提供的的locale,pinyin,stroke是bibmap根据unicode-cldr实现的排序
'sortascending':[True,False],#排序使用升序还是降序,默认是升序,设置为False则为降序
"date":['year','iso','ymd'],#'日期处理选项':year,iso,等
"urldate":['year','iso','ymd'],#'日期处理选项':year,iso,等
"origdate":['year','iso','ymd'],#'日期处理选项':year,iso,等
"eventdate":['year','iso','ymd'],#'日期处理选项':year,iso,等
'caseformat':['none','sentencecase','titlecase','uppercase','lowercase','smallcaps'],#设计'none','sentencecase','titlecase','uppercase','lowercase','smallcaps'
'numberformat':['ordinal','arabic'],#设计'ordinal','arabic'
'citesorting':'none', #标注中标签排序的选项所用的域,['key','author','year','title']
'backref':['true','false']
}
#
#格式化参考文献所用的域格式设置时的关键词数据库
#用于检查用户对域格式进行设置的问题
keyoptiondatabase=[
"fieldsource",
'options',
'prepunct',
'prepunctifnolastfield',
'prestringifnumber',
'posstringifnumber',
'replstring',
"posstring",
"prestring",
"omitifnofield",
"omitiffield",
'pospunct',
"position" #增加一个选项用于描述上标还是下标
]
#输入文件信息的全局变量
inputbibfile=''
inputauxfile=''
inputstyfile=''
inputmapfile=''
bibliotableflag='false' #输出表格形式的参考文献表的内容的标识
bmpsortcitesflag='false'
bmpcompcitesflag='false'
bmpbackrefflag='false'
sortfieldlist=[] #排序用列表
#记录文献信息的全局变量
bibentries=[] #用于记录所有条目,是列表
bibliographytext={} #引用的文献格式化后文献表条目的内容,是字典
FomattedBibentries={} #格式化后的所有文献条目信息,是字典
#
#
#打印格式化后的全部文献条目文本
def printbibliography(refsection=0):
global inputbibfile,inputauxfile,inputstyfile,inputmapfile,bibliotableflag,bibliographyenv
#md文件输出,直接用write写
mdoutfile=inputbibfile.replace('.bib','newformatted.txt')
fout = open(mdoutfile, 'w', encoding="utf8")
print("INFO: writing cited references to '" + mdoutfile + "'")
newbibliographytext=copy.deepcopy(bibliographytext)
for biblabelnumber in range(1,len(SortedEntryKeys)+1):
entrykey=SortedEntryKeys[biblabelnumber]
prtbibentry=newbibliographytext[entrykey]
if len(prtbibentry)>0:
#print(prtbibentry)
#\allowbreak字符串的替换
if r'\allowbreak' in prtbibentry:
prtbibentry=re.sub(r'\\allowbreak','',prtbibentry)
#\newblock字符串的替换
if r'\newblock' in prtbibentry:
prtbibentry=re.sub(r'\\newblock','',prtbibentry)
#\url字符串的替换
if r'\url' in prtbibentry:
prtbibentry=re.sub(r'\\url','',prtbibentry)
#\doi字符串的替换
if r'\doi' in prtbibentry:
prtbibentry=re.sub(r'\\doi','',prtbibentry)
#print(prtbibentry)
#sys.exit(-1)
fout.write('['+str(biblabelnumber)+'] '+prtbibentry+'\n')
fout.close()
#html文件输出,直接用write写
mdoutfile=inputbibfile.replace('.bib','newformatted.html')
fout = open(mdoutfile, 'w', encoding="utf8")
print("INFO: writing cited references to '" + mdoutfile + "'")
fout.write('<html><head><title>references</title></head>')
fout.write('<body bgcolor="lightgray"><div align="top"><center>')
fout.write('<font color="blue">')
fout.write('<table border="0" cellPadding="10" cellSpacing="5" height="400" width="70%">')
fout.write('<tr><td height="1" width="566" align="center" colspan="1" bgcolor="teal"></td></tr>')
for biblabelnumber in range(1,len(SortedEntryKeys)+1):
entrykey=SortedEntryKeys[biblabelnumber]
prtbibentry=newbibliographytext[entrykey]
if len(prtbibentry)>0:
#\allowbreak字符串的替换
if r'\allowbreak' in prtbibentry:
prtbibentry=re.sub(r'\\allowbreak','',prtbibentry)
#\newblock字符串的替换
if r'\newblock' in prtbibentry:
prtbibentry=re.sub(r'\\newblock','',prtbibentry)
#\url字符串的替换
if r'\url' in prtbibentry:
prtbibentry=re.sub(r'\\url','',prtbibentry)
#\doi字符串的替换
if r'\doi' in prtbibentry:
prtbibentry=re.sub(r'\\doi','',prtbibentry)
fout.write('<tr> <td width="480" height="15" colspan="6"><font color="blue">')
fout.write('<span style="font-family: 宋体; font-size: 14">')
fout.write('['+str(biblabelnumber)+'] '+prtbibentry)
fout.write('</span></font></td> </tr>')
fout.write('<tr><td height="1" width="566" align="center" colspan="1" bgcolor="teal"></td></tr>')
fout.write('</table></div></body></html>')
fout.close()
#bbl文件输出,直接用write写
if inputauxfile:
bblfile=inputauxfile.replace('.aux',f'refsec{refsection}.bbl')
else:
bblfile=inputbibfile.replace('.bib',f'refsec{refsection}.bbl')
inputauxfile=inputbibfile.replace('.bib','.aux')
bbloutfile=bblfile
#写入bbl文件中
#1. 为表格化文献表增加的输出信息
fout = open(bbloutfile, 'w', encoding="utf8") #inputauxfile
print("INFO: writing citation info to '" + bbloutfile + "'")
fout.write('\\ExplSyntaxOn\n')
fout.write('\\bibmapwriteExplon\n')
entrynum=0
for entrykey,prtbibentry in bibliographytext.items():
entrynum+=1
fout.write(r'\bibmapciteb:nn{'+entrykey+'}{'+str(entrynum)+'}\n')
#fout.write(r'\bibcite{'+entrykey+'}{'+str(entrynum)+'}\n')
#2. 为各类自定义标注标签添加的输出信息
formatcitation(refsection) #先处理
print("INFO: writing multi citation info to '" + bbloutfile + "'")
fout.write('\\makeatletter\n')
for clabel in CitationLabels:
strtemp1=clabel
strtemplst=strtemp1.split('\\')
strtemp2="\\"+("\\noexpand\\".join(strtemplst[1:]))
fout.write(strtemp2+'\n')
fout.write('\\makeatother\n')
fout.write('\\ExplSyntaxOff\n')
fout.write('\\bibmapwriteExploff\n')
#print('bibliographyenv=',bibliographyenv)
if not bibliotableflag:
fout.writelines(bibliographyenv['default'])
else:
fout.write(r'\renewcommand{\bibitem}[2][]{\mkbibbracket{\csuse{Bibmap@#2:}}}'+'\n')
if bibliotableflag!="tabularray":
fout.write(bibliographyenv['longtable']['cmd']+'\n')
fout.write(r'\renewenvironment{thebibliography}[1]'+'\n')
fout.write(r'{\begin{'+bibliographyenv['longtable']['env']+'}'+bibliographyenv['longtable']['colspec']+'\n'
+r'\hline'+'\n'+bibliographyenv['longtable']['head']+r'\\ \hline}')
fout.write(r'{\end{'+bibliographyenv['longtable']['env']+'}}\n')
else:
fout.write(bibliographyenv['tabularray']['cmd']+'\n')
fout.write(r'\RenewDocumentEnvironment{thebibliography}{m +b}'+'\n')
fout.write(r'{\begin{'+bibliographyenv['tabularray']['env']+'}'+bibliographyenv['tabularray']['colspec']+'\n'
+r'\hline'+'\n'+bibliographyenv['tabularray']['head']+r'\\ \hline\relax'+"\n"+'#2\n'+r'\end{'+bibliographyenv['tabularray']['env']+'}}')
fout.write('{}\n')
fout.close()
fout = open(bbloutfile, 'a', encoding="utf8")
print("INFO: writing cited references to '" + bbloutfile + "'")
fout.write('\n'+r'\begin{thebibliography}{'+str(len(bibliographytext))+'}\n')
#print('SortedEntryKeys=',SortedEntryKeys)
#anykey=input()
for biblabelnumber in range(1,len(SortedEntryKeys)+1):
entrykey=SortedEntryKeys[biblabelnumber]
prtbibentry=newbibliographytext[entrykey]
#print(f'{entrykey=}\n {prtbibentry=}')
if len(prtbibentry)>0:
entrykeystr=entrykey
#增加对文献条目集的处理
entrykey1="NotAsetenty"
if entrykey in EntrySet:
entrykey1=EntrySet[entrykey][0]
entrycitelabel=''
#仅当'labelname'选项存在时处理
if 'labelname' in formatoptions:
for bibentry in bibentries:
if bibentry['entrykey']==entrykey or bibentry['entrykey']==entrykey1:
entryciteauthor=formatlabelauthor(bibentry)
if 'labelyear' in bibentry:
entryciteyear=bibentry['labelyear']
else:
entryciteyear='N.d.'
if 'labelextrayear' in bibentry: #formatlabelyear(bibentry)
entryciteyear=entryciteyear+bibentry['labelextrayear']
entrycitelabel=entryciteauthor[0]+'('+entryciteyear+')'+entryciteauthor[1]
#Baker et~al.(1995) Baker and Jackson
break
if bmpbackrefflag:
backrefeach=[r"\hyperlink{page."+x+"}{"+x+"}" for x in EntryRefPages[entrykey]]
language=fieldlanguage(FomattedBibentries[entrykey]['title'])
backrefstr=localstrings['backref'][language]+r"\multilinkdelim".join(backrefeach)
else:
backrefstr=''
if bibliotableflag:
#表格形式
if 'labelname' in formatoptions:
fout.write(r'\relax'+r'\bibitem['+entrycitelabel+']{'+entrykeystr+r'} & '+r'\hypertarget{bib:label:'+f'{refsection}:'
+entrykeystr+'}{}'+prtbibentry+backrefstr+r'\\ \hline'+'\n')
else:
fout.write(r'\relax'+r'\bibitem['+str(biblabelnumber)+']{'+entrykeystr+r'} & '+r'\hypertarget{bib:label:'+f'{refsection}:'
+entrykeystr+'}{}'+prtbibentry+backrefstr+r'\\ \hline'+'\n')
else:
if 'labelname' in formatoptions:
fout.write(r'\relax'+r'\bibitem['+entrycitelabel+']{'+entrykeystr+'}'+r'\hypertarget{bib:label:'+f'{refsection}:'
+entrykeystr+'}{}'+prtbibentry+backrefstr+'\n')
else:
fout.write(r'\relax'+r'\bibitem['+str(biblabelnumber)+']{'+entrykeystr+'}'+r'\hypertarget{bib:label:'+f'{refsection}:'
+entrykeystr+'}{}'+prtbibentry+backrefstr+'\n')
fout.write(r'\end{thebibliography}')
fout.close()
return None
#
# 为所有样式标注标签的提供信息
#
def formatcitation(refsection=0):
global CitationLabels
global sortfieldlist
global currefsection
currefsection=refsection #当前文献节的序号存到全局变量currefsection中备用
CitationLabels=[]
recAllctnLabels={}
for et,ets in FomattedBibentries.items():#每条文献遍历
#print('et=',et)
#print('ets=',ets)
recAllctnLabels[et]={}
for st,style in citationstyle.items():#每种标注样式遍历
if style:#当样式设置存在时做
recstCitationLabels={}
#先做一遍具体设置的命令
for cmd,cmdsetstyle in style.items():#每个命令遍历
if not isinstance(cmdsetstyle,str) and cmdsetstyle: #命令的输出内容设置不是一个字符串,也就不是命令等价设置,且设置不为空
citestring=''
lastfield=False #前一域存在
for fieldinfo in cmdsetstyle:
fieldtext,lastfield=formatfield(ets,fieldinfo,lastfield)
citestring=citestring+fieldtext
citestring=citestring.replace(" ","\\space ")
recstCitationLabels[cmd]=citestring
CitationLabels.append("\\bmpbbl"+"@x"+cmd+"@"+st+":nnn{"+et+"}{"+str(refsection)+"}{"+citestring+"}")
recAllctnLabels[et][st]=recstCitationLabels
#再做一遍设置等价的命令
for cmd,cmdsetstyle in style.items():#每个命令遍历
if isinstance(cmdsetstyle,str):
citestring=recstCitationLabels[cmdsetstyle]
CitationLabels.append("\\bmpbbl"+"@x"+cmd+"@"+st+":nnn{"+et+"}{"+str(refsection)+"}{"+citestring+"}")
#print('test-4:anykey to continue')
#anykey=input()
#处理entrykey列表引用时的标注标签
recMulticites={}
for st in citationstyle.keys():
recMulticites[st]={}
for multicites in usedMctn:
eachcites=multicites.split(',')
#print('eachcites=',eachcites)
if bmpsortcitesflag:
if formatoptions['citesorting']!='none': #标注标签的排序,若给定排序的域
sortfieldlist=formatoptions['citesorting']
eachcites=sortEntriesALL(eachcites,True)
for st,style in citationstyle.items():#每种标注样式遍历
#print('\nst',st,style)
if style:#当样式设置存在时做
for cmd,cmdsetstyle in style.items():#每个命令遍历
if (not isinstance(cmdsetstyle,str)) and (cmdsetstyle[0]['fieldsource'][0]=='labelnumber' or cmdsetstyle[0]['fieldsource'][0]=='sortlabelnumber'):
fieldcontents=''
eachlabelnumbers=[int(FomattedBibentries[et][cmdsetstyle[0]['fieldsource'][0]]) for et in eachcites]
if bmpcompcitesflag:
#做数字的压缩处理
eachlabelnumbers.sort()
eachlabelnumbers1=[r'\hyperlink{bib:label:'+f'{refsection}:'+eachcites[0]+'}{'+str(eachlabelnumbers[0])+'}']
flag_continousNum=1
for i in range(1,len(eachlabelnumbers)):
if eachlabelnumbers[i]==eachlabelnumbers[i-1]+1:
flag_continousNum+=1
if flag_continousNum>=formatoptions['citecompstart'] and i==len(eachlabelnumbers)-1:
eachlabelnumbers1.append('-'+r'\hyperlink{bib:label:'+f'{refsection}:'+eachcites[i]+'}{'+str(eachlabelnumbers[i])+'}') #数字的压缩
else:
if flag_continousNum>=formatoptions['citecompstart']:
eachlabelnumbers1.append('-'+r'\hyperlink{bib:label:'+f'{refsection}:'+eachcites[i-1]+'}{'+str(eachlabelnumbers[i-1])+'}')
eachlabelnumbers1.append('\\multicitedelim'+cmd+" "+r'\hyperlink{bib:label:'+f'{refsection}:'+eachcites[i-1]+'}{'+str(eachlabelnumbers[i])+'}')
flag_continousNum=1
eachlabelnumbers=eachlabelnumbers1
print('eachlabelnumbers=',eachlabelnumbers)
fieldcontents="".join([str(x) for x in eachlabelnumbers])
else:
fieldcontents=('\\multicitedelim'+cmd+" ").join([r'\hyperlink{bib:label:'+f'{refsection}:'+eachcites[i]+'}{'+str(eachlabelnumbers[i])+'}' for i in range(len(eachlabelnumbers))])
citestring=''
lastfield=False #前一域存在
#这里其实默认了前面处理以后所有的域都变为fieldcontents了。
for fieldinfo in cmdsetstyle:
fieldtext=formatfieldFB(fieldcontents,fieldinfo,lastfield)
fieldtext=formatfieldRPL(fieldtext,fieldinfo)
citestring=citestring+fieldtext
lastfield=True
citestring=citestring.replace(" ","\\space ")
CitationLabels.append("\\bmpbbl"+"@x"+cmd+"@"+st+":nnn{"+multicites+"}{"+str(refsection)+"}{"+citestring+"}")
recMulticites[st][cmd]=citestring
elif (not isinstance(cmdsetstyle,str)) and cmdsetstyle[0]['fieldsource'][0]=='labelname':
if len(cmdsetstyle)>1 and cmdsetstyle[1]['fieldsource'][0]=='labelyear' and bmpcompcitesflag:
eachlabelnames=[FomattedBibentries[et]['labelname'] for et in eachcites]
eachlabelyears=[FomattedBibentries[et]['labelyear'] for et in eachcites]
tmp_flambda=lambda x,y: x[y] if y in x else ""
eachlabelextrs=[tmp_flambda(FomattedBibentries[et],'labelextrayear') for et in eachcites]
eachlabelnames1=[eachlabelnames[0]]
eachlabelyears1=[eachlabelyears[0]+eachlabelextrs[0]]
for i in range(1,len(eachlabelnames)):
if eachlabelnames[i]==eachlabelnames[i-1]:
eachlabelyears1[-1]+='\\multiciteyeardelim '+eachlabelyears[i]+eachlabelextrs[i]
else:
eachlabelnames1.append(eachlabelnames[i])
eachlabelyears1.append(eachlabelyears[i]+eachlabelextrs[i])
print('eachlabelnames1=',eachlabelnames1)
print('eachlabelyears1=',eachlabelyears1)
citestring=''
#这里其实默认了前面处理以后所有的域都变为fieldcontents了。
for i in range(len(eachlabelnames1)):
j=0
lastfield=False #前一域存在
for fieldinfo in cmdsetstyle:
if j==0:
fieldtext=formatfieldFB(eachlabelnames1[i],fieldinfo,lastfield)
fieldtext=formatfieldRPL(fieldtext,fieldinfo)
elif j==1:
fieldtext+=formatfieldFB(eachlabelyears1[i],fieldinfo,lastfield)
#print('fieldtext',fieldtext)
fieldtext=formatfieldRPL(fieldtext,fieldinfo)
#print('fieldtext',fieldtext)
elif fieldinfo['fieldsource'][0]=='labelextrayear':
pass
else:
fieldtext+=formatfield(ets,fieldinfo,lastfield)[0]
lastfield=True
j+=1
if i==0:
citestring=fieldtext
else:
citestring+="\\multicitedelim "+fieldtext
print('citestring=',citestring)
citestring=citestring.replace(" ","\\space ")
CitationLabels.append("\\bmpbbl"+"@x"+cmd+"@"+st+":nnn{"+multicites+"}{"+str(refsection)+"}{"+citestring+"}")
recMulticites[st][cmd]=citestring
else:
citestring=("\\multicitedelim"+cmd+" ").join([recAllctnLabels[et.strip()][st][cmd] for et in eachcites])
CitationLabels.append("\\bmpbbl"+"@x"+cmd+"@"+st+":nnn{"+multicites+"}{"+str(refsection)+"}{"+citestring+"}")
else:
if cmdsetstyle and isinstance(cmdsetstyle,str):
if cmdsetstyle in recMulticites[st]:
CitationLabels.append("\\bmpbbl"+"@x"+cmd+"@"+st+":nnn{"+multicites+"}{"+str(refsection)+"}{"+recMulticites[st][cmdsetstyle]+"}")
else:
citestring=("\\multicitedelim"+cmd+" ").join([recAllctnLabels[et.strip()][st][cmdsetstyle] for et in eachcites])
CitationLabels.append("\\bmpbbl"+"@x"+cmd+"@"+st+":nnn{"+multicites+"}{"+str(refsection)+"}{"+citestring+"}")
else:
citestring=("\\multicitedelim"+cmd+" ").join([recAllctnLabels[et.strip()][st][cmd] for et in eachcites])
CitationLabels.append("\\bmpbbl"+"@x"+cmd+"@"+st+":nnn{"+multicites+"}{"+str(refsection)+"}{"+citestring+"}")
return None
#
#authoryear样式提供标注标签的作者信息
#
def formatlabelauthor(bibentry):
#print('bibentry=',bibentry)
#从formatoptions["labelname"]获取备选域
fieldexistflag=False
for field in formatoptions["labelname"]:
if field in bibentry:
namelist=bibentry[field]
fieldexistflag=True
break
if not fieldexistflag:#citation尽管使用Anon并不合适,但作为最后的手段
return ['Anon','Anon']
incitenamelist=bibentry['labelname']
citenamelist=replacestrLabelname(incitenamelist)
return [citenamelist,namelist]
#
#替换labelname中的标点和字符串
def replacestrLabelname(incitenamelist):
citenamelist=incitenamelist
#自定义标点的处理
while r'\printdelim' in citenamelist:
m = re.search(r'\\printdelim{([^\}]*)}',citenamelist)#注意贪婪算法的影响,所以要排除\}字符
citenamelist=re.sub(r'\\printdelim{[^\}]*}',localpuncts[m.group(1)],citenamelist,count=1)
#本地化字符串的处理
while r'\bibstring' in citenamelist:
language=fieldlanguage(citenamelist)
#m = re.search(r'\\bibstring{([^\}]*)}',citenamelist)#注意\字符的匹配,即便是在r''中也需要用\\表示
#citenamelist=re.sub(r'\\bibstring{[^\}]*}',localstrings[m.group(1)][language],citenamelist,count=1)
m = re.search(r'\\bibstring\{(.*?)\}',citenamelist)#注意\字符的匹配,即便是在r''中也需要用\\表示
#print('m.group(1)',m.group(1))
localstringkey=m.group(1)
m =re.search(r'(\\bibstring\{.*?\})',citenamelist)
citenamelist=citenamelist.replace(m.group(1),localstrings[localstringkey][language])
return citenamelist
#
#authoryear样式提供标注标签的年份信息
#
def formatlabelyear(bibentry):
#从formatoptions["labelyear"]获取备选域
fieldexistflag=False
for field in formatoptions["labelyear"]:
if field in bibentry:
yearlist=bibentry[field]
fieldexistflag=True
break
if not fieldexistflag:#
return 'N.d'
return yearlist
#
#
#格式化全部文献条目文本
def formatallbibliography():
global FomattedBibentries,bibentries
global bibliographytext
global sortfieldlist
global curentrykey #当前的条目的entrykey
bibliographytext={}
#
#1. 将引用的文献存到一个新的列表中,便于排序
newbibentries=[]
if usedIds:
#首先根据引用顺序给出labelnumber从1开始计数
labelnumberdict={} #记录对应labelnumber
labelnumber=0
for entrykey in usedIds:
labelnumber=labelnumber+1
labelnumberdict[entrykey]=labelnumber
#print(f'{labelnumberdict=}')
#对所有条目设置一个labelnumber域,记录引用顺序
#注意:条目集中的第一条文献的labelnumber是条目集的labelnumber,其他文献则按添加仅usedids的顺序给出
for bibentry in bibentries:
if bibentry["entrykey"] in usedIds:
bibentry['labelnumber']=labelnumberdict[Entrysetkey(bibentry["entrykey"])]
newbibentries.append(bibentry)
else:
#当usedIds为空时,则按bib文件中的顺序给出labelnumber
labelnumber=0
bibentrynotsame=set()
for bibentry in bibentries:
if bibentry["entrykey"] not in bibentrynotsame:
labelnumber=labelnumber+1
bibentry['labelnumber']=labelnumber
bibentrynotsame.add(bibentry["entrykey"])
newbibentries.append(bibentry)
#print('1-test-------------------:')
#print('usedIds=',usedIds)
#for x in newbibentries:
# print(x)
#print('1-test-:anykey to continue')
#anykey=input()
print('INFO: '+str(labelnumber)+'s references to be outputed')
#
#2. 格式化之前先处理完需要解析的范围域和日期域
# 先处理完文献语言以及排序问题
#
#sortfieldlist用于保存排序的域
sortfieldlist=[]#
if formatoptions['lanorder']=='none':
pass
else:
print('INFO: sorting with language as the first key')
sortfieldlist.append('sortlang')#第一个排序域是文种,这里用sortlang来进行文种的排序
sortlangdict={}#用于设置对应的语言的排序数字
tempserialno=1
for lan in formatoptions['lanorder']:
sortlangdict[lan]=tempserialno
tempserialno+=1
sortfieldlist.append('sortkey')#第二个排序域是key/sortkey,用sortkey表示用key/sortkey进行排序
print('INFO: sorting with sortkey as the second key')
sortingflag=True #标记一下便于后面判断
print('INFO: sorting with fields',formatoptions['sorting'])
if formatoptions['sorting']=='none':#如果sorting选项不为none,那么将其设置的域作为接下来的排序域来排序
sortingflag=False
else:
for field in formatoptions['sorting']:
sortfieldlist.append('sort'+field)
for bibentry in newbibentries:
#
# 由于volume和number域可能存在范围的特殊情况,首先做特殊处理
#
if 'volume' in bibentry:
if '-' in bibentry['volume']:
multivolume=bibentry['volume'].split("-")
bibentry['volume']=multivolume[0]
bibentry['endvolume']=multivolume[1]
if 'number' in bibentry:
if '-' in bibentry['number']:
multinumber=bibentry['number'].split("-")
bibentry['number']=multinumber[0]
bibentry['endnumber']=multinumber[1]
#
#四种日期域也做范围解析
#year本来作为不可解析的日期存放的域
#但有时老的bib文件会把year和date混用,因此仅存在year域时也需要解析
#将[datetype]date域解析以后,则删除这些域,仅保留[datetype]year|month|day
if 'year' in bibentry:
if '/' in bibentry['year']:
datestring=bibentry['year'].split('/')
bibentry['year']=datestring[0]
bibentry['endyear']=datestring[1]
#print('year=',bibentry['year'])
#print('endyear=',bibentry['endyear'])
dateparts,datetype=datetoymd(bibentry,'year')
for k,v in dateparts.items():
bibentry[k]=v
dateparts,datetype=datetoymd(bibentry,'endyear')
for k,v in dateparts.items():
bibentry[k]=v
else:
dateparts,datetype=datetoymd(bibentry,'year')
for k,v in dateparts.items():
bibentry[k]=v
if 'date' in bibentry:
if '/' in bibentry['date']:
datestring=bibentry['date'].split('/')
bibentry['date']=datestring[0]
bibentry['enddate']=datestring[1]
#print('date=',bibentry['date'])
#print('enddate=',bibentry['enddate'])
dateparts,datetype=datetoymd(bibentry,'date')
for k,v in dateparts.items():
bibentry[k]=v
dateparts,datetype=datetoymd(bibentry,'enddate')
for k,v in dateparts.items():
bibentry[k]=v
del bibentry['date']
del bibentry['enddate']
else:
dateparts,datetype=datetoymd(bibentry,'date')
for k,v in dateparts.items():
bibentry[k]=v
del bibentry['date']
if 'urldate' in bibentry:
if '/' in bibentry['urldate']:
datestring=bibentry['urldate'].split('/')
bibentry['urldate']=datestring[0]
bibentry['endurldate']=datestring[1]
dateparts,datetype=datetoymd(bibentry,'urldate')
for k,v in dateparts.items():
bibentry[k]=v
dateparts,datetype=datetoymd(bibentry,'endurldate')
for k,v in dateparts.items():
bibentry[k]=v
del bibentry['urldate']
del bibentry['endurldate']
else:
dateparts,datetype=datetoymd(bibentry,'urldate')
for k,v in dateparts.items():
bibentry[k]=v
del bibentry['urldate']
if 'eventdate' in bibentry:
if '/' in bibentry['eventdate']:
datestring=bibentry['eventdate'].split('/')
bibentry['eventdate']=datestring[0]
bibentry['endeventdate']=datestring[1]
dateparts,datetype=datetoymd(bibentry,'eventdate')
for k,v in dateparts.items():
bibentry[k]=v
dateparts,datetype=datetoymd(bibentry,'endeventdate')
for k,v in dateparts.items():
bibentry[k]=v
del bibentry['eventdate']
del bibentry['endeventdate']
else:
dateparts,datetype=datetoymd(bibentry,'eventdate')
for k,v in dateparts.items():
bibentry[k]=v
del bibentry['eventdate']
if 'origdate' in bibentry:
if '/' in bibentry['origdate']:
datestring=bibentry['origdate'].split('/')
bibentry['origdate']=datestring[0]
bibentry['endorigdate']=datestring[1]
dateparts,datetype=datetoymd(bibentry,'origdate')
for k,v in dateparts.items():
bibentry[k]=v
dateparts,datetype=datetoymd(bibentry,'endorigdate')
for k,v in dateparts.items():
bibentry[k]=v
del bibentry['origdate']
del bibentry['endorigdate']
else:
dateparts,datetype=datetoymd(bibentry,'origdate')
for k,v in dateparts.items():
bibentry[k]=v
del bibentry['origdate']
#
#接着判断一下文献的整体语言情况,方便后面一些域格式化时的处理,当然有些域比如作者还需要根据域本身进行判断
#
if 'language' in bibentry:#存在language域则不做处理
pass
elif 'title' in bibentry:#若不存在则首先title域做判断
language=languagejudgement(bibentry,'title')
bibentry['language']=language
'''
if 'language' in bibentry:
print('language of bibentry: ',bibentry['entrykey'],' is: ',bibentry['language'])
else:
print('language of bibentry: ',bibentry['entrykey'],' is: none')
'''
#
#2.1 姓名列表的歧义的处理,先于排序
#仅当'labelname'选项存在时处理
if 'labelname' in formatoptions:
for bibentry in newbibentries:
#姓名列表标签备选域处理
fieldlabelname=''
for field in formatoptions['labelname']:
if field in bibentry:
fieldlabelname=field
break
if not fieldlabelname:
print('INFO: warning label name field is not defined')
bibentry['noauthor']='Anon'
fieldlabelname='noauthor'
#年份标签备选域处理
fieldlabelyear=''
for field in formatoptions['labelyear']:
if field in bibentry:
fieldlabelyear=field
break
if not fieldlabelyear:
print('INFO: warning label name field is not defined')
bibentry['noyear']='N.D.'
fieldlabelyear='noyear'
#先把姓名列表解析处理存储起来,便于后面处理
bibentry['labelnameraw']=labelnamelistparser(bibentry,fieldlabelname)
bibentry['labelyearraw']=bibentry[fieldlabelyear]
#处理姓名列表的模糊问题
newbibentries=dealambiguity(newbibentries)
for bibentry in newbibentries:
#格式化labelname,labelyear。而labelextrayear还得等排序以后才能得到
bibentry['labelname']=labelnameformat(bibentry)
bibentry['labelyear']=bibentry['labelyearraw']
#print('entry:',bibentry['entrykey'])
#print('labelname=',bibentry['labelname'])
#print('labelyear=',bibentry['labelyear'])
print('INFO: label name year info updated ')
#print('test-1-1:any key to continue')
#anykey=input()
#
#2.2 排序的域的信息的准备
for bibentry in newbibentries:
#
#接着处理排序的前期准备工作,根据全局的排序设置选项,在条目中保存排序需要的信息
#
if sortingflag:
#首先处理sortlan域的信息
if 'sortlang' in sortfieldlist:
bibentry['sortlang']=sortlangdict[bibentry['language']]
#接着处理sortkey域的信息
if 'key' in bibentry:
bibentry['sortkey']=bibentry['key']
else:
bibentry['sortkey']=''
#接着处理各个排序域的信息
for fieldsource in formatoptions['sorting']:
if fieldsource in bibentry:
#bibentry['sort'+field]=bibentry[field]
#当域为姓名列表域时:
if fieldsource in datatypeinfo['namelist']:
if 'options' in bibentry:
options=bibentry['options']#如果条目本身具有选项
else:
options={}
fieldcontents=namelistparser(bibentry,fieldsource,options)
#自定义标点的处理
while r'\printdelim' in fieldcontents:
m = re.search(r'\\printdelim{([^\}]*)}',fieldcontents)#注意贪婪算法的影响,所以要排除\}字符
fieldcontents=re.sub(r'\\printdelim{[^\}]*}',localpuncts[m.group(1)],fieldcontents,count=1)
#当域为文本列表域时:
elif fieldsource in datatypeinfo['literallist']:
fieldcontents=literallistparser(bibentry,fieldsource)
#当域为文本域时:
elif fieldsource in datatypeinfo['literalfield']:
if 'options' in bibentry:
options=bibentry['options']#如果条目本身具有选项
else:
options={}
fieldcontents=literalfieldparser(bibentry,fieldsource,options)
#当域为日期域时:
elif fieldsource in datatypeinfo['datefield']:
fieldcontents=bibentry[fieldsource]
#当域为范围域时:
elif fieldsource in datatypeinfo['rangefield']:
fieldcontents=rangefieldparser(bibentry,fieldsource)
else:
fieldcontents=bibentry[fieldsource]
bibentry['sort'+fieldsource]=fieldcontents
else:
bibentry['sort'+fieldsource]=''
#
#print('test-2--------------------:')
#3. 接着根据排序信息对条目进行排序
global SortedEntryKeys #记录entrykey及其对应的sortlabelnumber
SortedEntryKeys={} #key是sortlabelnumber, v是entrykey
if sortingflag:
print('INFO: sort executed')
newbibentries=sortEntriesALL(newbibentries,False)
sortlabelnumber=0
for entry in newbibentries:
if not InEntryset(entry['entrykey']):
sortlabelnumber+=1
entry['sortlabelnumber']=sortlabelnumber
SortedEntryKeys[sortlabelnumber]=entry['entrykey']
else: #若不排序,则'sortlabelnumber'等于'labelnumber'
print('INFO: sort unexecuted')
for entry in newbibentries:
sortlabelnumber=entry['labelnumber']
entry['sortlabelnumber']=sortlabelnumber
if not InEntryset(entry['entrykey']):
SortedEntryKeys[sortlabelnumber]=entry['entrykey']
print('INFO: label number updated in sortlabelnumber after sorting')
#print(f'{SortedEntryKeys=}')
#print('test-2:any key to continue')
#anykey=input()
#
#3.1 接着根据排序条目处理labelextrayear
#仅当'labelname'选项存在时处理
if 'labelname' in formatoptions:
extrayearrawdict={}
for bibentry in newbibentries:
if 'labelextrayearraw' in bibentry:
extrayearkey=str(bibentry['labelextrayearraw'])
if extrayearkey not in extrayearrawdict:
extrayearrawdict[extrayearkey]=1
bibentry['labelextrayearraw']=1
else:
extrayearrawdict[extrayearkey]+=1
bibentry['labelextrayearraw']=extrayearrawdict[extrayearkey]
for bibentry in newbibentries:
if 'labelextrayearraw' in bibentry:
if isinstance(bibentry['labelextrayearraw'],int):
bibentry['labelextrayear']=setnumberalpha(bibentry['labelextrayearraw'])
print('labelextrayear=',bibentry['labelextrayear'])
print('INFO: label year extra raw info updated ')
#print('test-3:any key to continue')
#anykey=input()
#sys.exit(-1)
#
#4. 将所有需要输出的文献进行格式化
FomattedBibentries={}
for bibentry in newbibentries:
bibentrytext=''
curentrykey=bibentry["entrykey"]
bibentrytext=formatbibentry(bibentry)
#为避免后面处理文献条目集的时候顺序出现问题
#直接在这里处理将第一个文献的条目entrykey换成条目集的key
ekidx,est=EntrykeyinDictV(bibentry["entrykey"],EntrySet)
if ekidx==0:
RplcDictVal(bibentry["entrykey"],est,SortedEntryKeys) #将SortedEntryKeys也替换为条目集的key
bibliographytext[est]=bibentrytext
bibentry["entrykey"]=est #将条目的entrykey切换为条目集的key
FomattedBibentries[est]=bibentry # 同时FomattedBibentries仅给出条目集的key
FomattedBibentries[est]["styletext"]=bibentrytext
else:
bibliographytext[bibentry["entrykey"]]=bibentrytext
FomattedBibentries[bibentry["entrykey"]]=bibentry
FomattedBibentries[bibentry["entrykey"]]["styletext"]=bibentrytext
#
#5. 条目集处理的,将条目集中除第一个文献外的所有文献文献信息附到第一条文献后面
# 然后将第一条文献的entrykey修改为条目集的entrykey,这个在上一步已经处理
# 条目集的排序按照第一条文献的排序即可
# 注意通常文献集,及其内部的文献是不会同时引用的,因为这是没有必要的。
for est,ekl in EntrySet.items():
for ek in ekl[1:]:
bibliographytext[est]=bibliographytext[est]+"\\entrysetpunct{}"+bibliographytext.pop(ek)
FomattedBibentries[est]["styletext"]=bibliographytext[est]
#将处理后的newbibentries存为初始的bibentries
bibentries=newbibentries
#
# 最后输出
#print('4-test-:anykey to continue')
print('\nReferecences:','\n'+'-'.center(50,'-'))
for k,v in bibliographytext.items():
print('entry id=',FomattedBibentries[k]['labelnumber'],
'sorted id=',FomattedBibentries[k]['sortlabelnumber'],
' bibtexkey="'+k+'"\n'+v,'\n'+'-'.center(50,'-'))
#print(FomattedBibentries[k])
#print('FomattedBibentries=',FomattedBibentries)