forked from hushidong/biblatex-gb7714-2015
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbiblatex-map.py
2059 lines (1727 loc) · 64.7 KB
/
biblatex-map.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宏包可以实现不同的标注样式。
"""
__author__ = "Hu zhenzhen"
__version__ = "1.0"
__license__ = "MIT"
__email__ = "[email protected]"
import string
import re
import sys
import datetime
import copy
import json
import operator
#
# 为数据map设置参数
# 选项的逻辑与biblatex基本一致,
# 差别包括:overwrite选项可以放到step步中表示
#[]=maps
#[[],[]]=map in maps
#[[[]],[]]=step in map in mpas
#[[[{optionkey: }]],[]]=step in map in mpas
#注意python正则表达方式与perl的略有不同,比如unicode表示
#python用\xHH,\uHHHH,\UHHHHHHHH表示,而perl直接用\x{HHHH}表示。
sourcemaps=[#maps
[#map1:将ELECTRONIC类型转换为online类型
[{"typesource":"ELECTRONIC","typetarget":"online"}]#step1
],
[#map2:将source域转换为url域
[{"fieldsource":"source","fieldtarget":"url"}]#step1
],
[#map3:将urldate域的信息“yyyy-m-d”转换为“yyyy-mm-dd”,注意正则表达式直接写不用在外面套""
[{"fieldsource":"urldate","match":r'(\d\d\d\d)\-(\d)\-(\d)',"replace":r'\1-0\2-0\3'}]#step1
],
[#map4:将urldate域的信息“yyyy-m-d”转换为“yyyy-mm-dd”,注意正则表达式直接写不用在外面套""
[{"fieldsource":"date","match":r'(\d\d\d\d)\-(\d)\-(\d)',"replace":r'\1-0\2-0\3',"overwrite":True}]#step1
],
[#map5:将refdate域转换为urldate域
[{"fieldsource":"refdate","fieldtarget":"urldate"}]#step1
],
[#map6:对于newspaper类型,设置note为news
[{"pertype":"newspaper"}],#step1
[{"fieldset":"note","fieldvalue":"news","overwrite":True}]#step2
],
[#map7:设置edition域等于version
[{"fieldsource":"version","final":True}],#step1
[{"fieldset":"edition","origfieldval":True}]#step2
],
[#map8:设置entrykey域设置给keywords
[{"fieldsource":"entrykey"}],#step1
[{"fieldset":"keywords","origfieldval":True}]#step2
],
[#map9:对于存在note域的情况,将其值添加到keywords
[{"fieldsource":"note","final":True}],#step1
[{"fieldset":"keywords","origfieldval":True,"overwrite":True,"append":True}]#step2
],
[#map10:根据标题的字符编码范围确定标题的语言类型
[{"fieldsource":"title","match":r'[\u2FF0-\u9FA5]',"final":True}],#step1
[{"fieldset":"userd","fieldvalue":"chinese"}]#step2
],
]
#重设新的任务处理
sourcemaps=[
[#map1:设置entrykey域设置给keywords
[{"fieldsource":"entrykey"}],#step1
[{"fieldset":"keywords","origfieldval":True,"overwrite":True}]#step2
],
]
#重设新的任务
sourcemaps=[
[#map1:取消note域
[{"fieldsource":"note","final":True}],#step1
[{"fieldset":"note","null":True,"overwrite":True}]#step2
],
[#map2:取消abstract域
[{"fieldsource":"abstract","final":True}],#step1
[{"fieldset":"abstract","null":True,"overwrite":True}]#step2
],
[#map3:取消keywords域
[{"fieldsource":"keywords","final":True}],#step1
[{"fieldset":"keywords","null":True,"overwrite":True}]#step2
],
[#map4:取消keywords-plus域
[{"fieldsource":"keywords-plus","final":True}],#step1
[{"fieldset":"keywords-plus","null":True,"overwrite":True}]#step2
],
[#map5:取消affiliation域
[{"fieldsource":"affiliation","final":True}],#step1
[{"fieldset":"affiliation","null":True,"overwrite":True}]#step2
],
[#map6:取消funding-acknowledgement域
[{"fieldsource":"funding-acknowledgement","final":True}],#step1
[{"fieldset":"funding-acknowledgement","null":True,"overwrite":True}]#step2
],
[#map7:取消funding-text域
[{"fieldsource":"funding-text","final":True}],#step1
[{"fieldset":"funding-text","null":True,"overwrite":True}]#step2
],
]
#重设不处理
sourcemaps=[]
##------------------------------------------
## 参考文献表的制定格式设置,比如GB/T 7714-2015
##
#全局选项
formatoptions={
"style":'authoryear',#写bbl信息的设置选项,authoryear,'numeric'
"nameformat":'uppercase',#姓名处理选项:uppercase,lowercase,given-family,family-given,pinyin
"giveninits":'space',#使用名的缩写,space表示名见用空格分隔,dotspace用点加空格,dot用点,terse无分隔,false不使用缩写
"maxbibnames":3,#
"minbibnames":3,#
"morenames":True,#
"maxbibitems":1,#
"minbibitems":1,#
"moreitems":False,#
"date":'year',#'日期处理选项':year,iso,等
"urldate":'iso',#'日期处理选项':year,iso,等
}
#本地化字符串
localstrings={
'andothers':{'english':'et al.','chinese':'等'},
'and':{'english':' and ','chinese':'和'},
'edition':{'english':'th ed','chinese':'版'},#th ed. 中的点不要,为方便标点处理
'in':{'english':'in: ','chinese':'见: '},
'nolocation':{'english':'[S.l.]','chinese':'[出版地不详]'},
'nopublisher':{'english':'[s.n.]','chinese':'[出版者不详]'},
'bytranslator':{'english':'trans by','chinese':'译'},
}
#标点
localpuncts={
'multinamedelim':', ',
'finalnamedelim':', ',
'andothorsdelim':', ',
'finalitemdelim':', ',
'multiitemdelim':', ',
}
#替换字符串
replacestrings={
'[出版地不详]: [出版者不详]':'[出版地不详 : 出版者不详]',
'[S.l.]: [s.n.]':'[S.l. : s.n.]',
'..':'.',
}
#类型和载体字符串
typestrings={
'book':'[M]',
'inbook':'[M]',
'standard':'[S]',
'periodical':'[J]',
'article':'[J]',
'newspaper':'[N]',
'patent':'[P]',
'online':'[EB]',
'www':'[EB]',
'electronic':'[EB]',
'proceedings':'[C]',
'inproceedings':'[C]',
'conference':'[C]',
'collection':'[G]',
'incollection':'[G]',
'thesis':'[D]',
'mastersthsis':'[D]',
'phdthesis':'[D]',
'report':'[R]',
'techreport':'[R]',
'manual':'[A]',
'archive/manual':'[A]',
'database':'[DB]',
'dataset':'[DS]',
'software':'[CP]',
'map':'[CM]',
'unpublished':'[Z]',
'misc':'[Z]',
}
#数据类型
datatypeinfo={
'namelist':['author','editor','translator','bookauthor'],
'literallist':['location','address','publisher','institution','organization','school','language','keywords'],
'literalfield':['title','journaltitle','journal','booktitle','subtitle','titleaddon','edition','version','url',
'volume','number','endvolume','endnumber','type','note','labelnumber'],
'datefield':['date','year','urldate','enddate','origdate','eventdate'],
'rangefield':['pages']
}
#条目的著录格式
bibliographystyle={
"book":[
#{"fieldsource":["labelnumber"],'prestring':"[","posstring":"]","pospunct":" "},
{"fieldsource":['author','editor','translator'],'options':{'nameformat':'uppercase'}},
{"fieldsource":['title'],'caseformat':'sentencecase','prepunct':". ",'prepunctifnolastfield':'','posstring':r"\typestring"},
{"fieldsource":['translator'],'options':{'nameformat':'uppercase'},'prepunct':". ",'posstring':r', \bibstring{bytranslator}'},
{"fieldsource":['edition'],'numerformat':'arabic','prepunct':". ","posstringifnumber":r'\bibstring{edition}'},
{"fieldsource":['location','address'],'prepunct':". ",'replstring':r"\bibstring{nolocation}"},
{"fieldsource":['publisher'],'prepunct':": ",'replstring':r"\bibstring{nopublisher}",'prepunctifnolastfield':'. '},
{"fieldsource":['date','year'],'prepunct':", "},
{"fieldsource":['pages'],'prepunct':": "},
{"fieldsource":['urldate'],'prestring':"[","posstring":"]"},
{"fieldsource":['url'],'prepunct':". ",'prestring':r'\url{','posstring':'}'},
{"fieldsource":['doi'],'prepunct':". "},
{"fieldsource":['endpunct'],'replstring':"."}
],
"article":[
#{"fieldsource":["labelnumber"],'prestring':"[","posstring":"]","pospunct":" "},
{"fieldsource":['author','editor','translator'],'options':{'nameformat':'uppercase'}},
{"fieldsource":['title'],'caseformat':'sentencecase','prepunct':". ",'prepunctifnolastfield':'','posstring':r"\typestring"},
{"fieldsource":['journaltitle','journal'],'prepunct':". "},
{"fieldsource":['year','date'],'prepunct':", "},
{"fieldsource":['volume'],'prepunct':", "},
{"fieldsource":['number'],'prestring':"(",'posstring':")"},
{"fieldsource":['pages'],'prepunct':": "},
{"fieldsource":['urldate'],'prestring':"[","posstring":"]"},
{"fieldsource":['url'],'prepunct':". "},
{"fieldsource":['doi'],'prepunct':". "},
{"fieldsource":['endpunct'],'replstring':"."}
],
"newspaper":[
#{"fieldsource":["labelnumber"],'prestring':"[","posstring":"]","pospunct":" "},
{"fieldsource":['author','editor','translator'],'options':{'nameformat':'uppercase'}},
{"fieldsource":['title'],'caseformat':'sentencecase','prepunct':". ",'prepunctifnolastfield':'','posstring':r"\typestring"},
{"fieldsource":['journaltitle','journal'],'prepunct':". "},
{"fieldsource":['date','year'],'prepunct':", ",'options':{'date':'iso'}},
{"fieldsource":['number'],'prestring':"(",'posstring':")"},
{"fieldsource":['pages'],'prepunct':": "},
{"fieldsource":['urldate'],'prestring':"[","posstring":"]"},
{"fieldsource":['url'],'prepunct':". "},
{"fieldsource":['doi'],'prepunct':". "},
{"fieldsource":['endpunct'],'replstring':"."}
],
"inbook":[
#{"fieldsource":["labelnumber"],'prestring':"[","posstring":"]","pospunct":" "},
{"fieldsource":['author','translator'],'options':{'nameformat':'uppercase'}},
{"fieldsource":['title'],'caseformat':'sentencecase','prepunct':". ",'prepunctifnolastfield':'','posstring':r"\typestring"},
{"fieldsource":['in'],'replstring':"//",'omitifnofield':['bookauthor','editor','booktitle']},
{"fieldsource":['bookauthor','editor'],'options':{'nameformat':'uppercase'}},
{"fieldsource":['booktitle'],'caseformat':'sentencecase','prepunct':". ",'prepunctifnolastfield':''},
{"fieldsource":['edition'],'numerformat':'arabic','prepunct':". ","posstring":r'\bibstring{edition}'},
{"fieldsource":['location','address'],'prepunct':". ",'replstring':r"\bibstring{nolocation}"},
{"fieldsource":['publisher'],'prepunct':": ",'replstring':r"\bibstring{nopublisher}",'prepunctifnolastfield':'. '},
{"fieldsource":['date','year'],'prepunct':", "},
{"fieldsource":['pages'],'prepunct':": "},
{"fieldsource":['urldate'],'prestring':"[","posstring":"]"},
{"fieldsource":['url'],'prepunct':". "},
{"fieldsource":['doi'],'prepunct':". "},
{"fieldsource":['endpunct'],'replstring':"."}
],
"inproceedings":"inbook",
"incollection":"inbook",
"standard":"inbook",
"proceedings":"book",
"collection":"book",
"patent":[
#{"fieldsource":["labelnumber"],'prestring':"[","posstring":"]","pospunct":" "},
{"fieldsource":['author'],'options':{'nameformat':'uppercase'}},
{"fieldsource":['title'],'caseformat':'sentencecase','prepunct':". ",'prepunctifnolastfield':'','posstring':r"\typestring"},
{"fieldsource":['number'],'prepunct':": "},
{"fieldsource":['date','year'],'prepunct':", "},
{"fieldsource":['urldate'],'prestring':"[","posstring":"]"},
{"fieldsource":['url'],'prepunct':". "},
{"fieldsource":['doi'],'prepunct':". "},
{"fieldsource":['endpunct'],'replstring':"."}
],
"online":[
#{"fieldsource":["labelnumber"],'prestring':"[","posstring":"]","pospunct":" "},
{"fieldsource":['author','editor','translator'],'options':{'nameformat':'uppercase'}},
{"fieldsource":['title'],'caseformat':'sentencecase','prepunct':". ",'prepunctifnolastfield':'','posstring':r"\typestring"},
{"fieldsource":['organization','instiution'],'prepunct':". "},
{"fieldsource":['date','year'],'prepunct':", ",'prepunctifnolastfield':'. ','omitifnofield':['enddate','eventdate']},
{"fieldsource":['pages'],'prepunct':": "},
{"fieldsource":['date','enddate','eventdate'],'prepunct':". ",'options':{"date":"iso",'eventdate':'iso'},'prestring':"(","posstring":")"},
{"fieldsource":['urldate'],'prestring':"[","posstring":"]",'prepunctifnolastfield':'. '},
{"fieldsource":['url'],'prepunct':". ",'prepunctifnolastfield':''},
{"fieldsource":['doi'],'prepunct':". "},
{"fieldsource":['endpunct'],'replstring':"."}
],
"www":"online",
"electronic":"online",
"report":[
#{"fieldsource":["labelnumber"],'prestring':"[","posstring":"]","pospunct":" "},
{"fieldsource":['author','editor','translator'],'options':{'nameformat':'uppercase'}},
{"fieldsource":['title'],'caseformat':'sentencecase','prepunct':". ",'prepunctifnolastfield':'','posstring':r"\typestring"},
{"fieldsource":['translator'],'options':{'nameformat':'uppercase'},'prepunct':". "},
{"fieldsource":['type'],'prepunct':". "},
{"fieldsource":['number'],'prepunct':"",'prepunctifnolastfield':'. '},
{"fieldsource":['version'],'prepunct':". "},
{"fieldsource":['location','address'],'prepunct':". ",'replstring':r"\bibstring{nolocation}"},
{"fieldsource":['institution','publisher'],'prepunct':": ",'replstring':r"\bibstring{nopublisher}",'prepunctifnolastfield':'. '},
{"fieldsource":['date','year'],'prepunct':", ",'omitifnofield':['location','address','institution','publisher'],'omitiffield':['url']},
{"fieldsource":['date','year'],'prepunct':". ",'prestring':'(','posstring':')','omitiffield':['location','address','institution','publisher']},
{"fieldsource":['pages'],'prepunct':": "},
{"fieldsource":['urldate'],'prestring':"[","posstring":"]"},
{"fieldsource":['url'],'prepunct':". "},
{"fieldsource":['doi'],'prepunct':". "},
{"fieldsource":['endpunct'],'replstring':"."}
],
"techreport":"report",
"periodical":[
#{"fieldsource":["labelnumber"],'prestring':"[","posstring":"]","pospunct":" "},
{"fieldsource":['editor','author'],'options':{'nameformat':'uppercase'}},
{"fieldsource":['title'],'caseformat':'sentencecase','prepunct':". ",'prepunctifnolastfield':'','posstring':r"\typestring"},
{"fieldsource":['year','date'],'prepunct':", "},
{"fieldsource":['volume'],'prepunct':", "},
{"fieldsource":['number'],'prestring':"(",'posstring':")-"},
{"fieldsource":['endyear','enddate'],'prepunct':", "},
{"fieldsource":['endvolume'],'prepunct':", "},
{"fieldsource":['endnumber'],'prestring':"(",'posstring':")"},
{"fieldsource":['location','address'],'prepunct':". ",'replstring':r"\bibstring{nolocation}"},
{"fieldsource":['institution','publisher'],'prepunct':": ",'replstring':r"\bibstring{nopublisher}",'prepunctifnolastfield':'. '},
{"fieldsource":['year','date'],'prepunct':", ",'posstring':'-'},
{"fieldsource":['pages'],'prepunct':": "},
{"fieldsource":['urldate'],'prestring':"[","posstring":"]"},
{"fieldsource":['url'],'prepunct':". "},
{"fieldsource":['doi'],'prepunct':". "},
{"fieldsource":['endpunct'],'replstring':"."}
],
#omitifnofield:必须所有的域都不存在才为true
#omitiffield:只要存在一个域就为true
"thesis":[
#{"fieldsource":["labelnumber"],'prestring':"[","posstring":"]","pospunct":" "},
{"fieldsource":['author','editor','translator'],'options':{'nameformat':'uppercase'}},
{"fieldsource":['title'],'caseformat':'sentencecase','prepunct':". ",'prepunctifnolastfield':'','posstring':r"\typestring"},
{"fieldsource":['translator'],'options':{'nameformat':'uppercase'},'prepunct':". "},
{"fieldsource":['location','address'],'prepunct':". "},
{"fieldsource":['institution','publisher','school'],'prepunct':": ",'prepunctifnolastfield':'. '},
{"fieldsource":['date','year'],'prepunct':", ",'omitifnofield':['location','address','institution','publisher'],'omitiffield':['url']},
{"fieldsource":['date','year'],'prepunct':". ",'prestring':'(','posstring':')','omitiffield':['location','address','institution','publisher']},
{"fieldsource":['pages'],'prepunct':": "},
{"fieldsource":['urldate'],'prestring':"[","posstring":"]"},
{"fieldsource":['url'],'prepunct':". ",'prestring':r'\url{','posstring':'}'},
{"fieldsource":['doi'],'prepunct':". "},
{"fieldsource":['endpunct'],'replstring':"."}
],
"manual":"thesis",
"unpublished":"thesis",
"database":"thesis",
"dataset":"thesis",
"software":"thesis",
"map":"thesis",
"archive":"thesis",
"misc":[
#{"fieldsource":["labelnumber"],'prestring':"[","posstring":"]","pospunct":" "},
{"fieldsource":['author','editor','translator'],'options':{'nameformat':'uppercase'}},
{"fieldsource":['title'],'caseformat':'sentencecase','prepunct':". ",'prepunctifnolastfield':'','posstring':r"\typestring"},
{"fieldsource":['howpublished'],'prepunct':". "},
{"fieldsource":['location','address'],'prepunct':". "},
{"fieldsource":['institution','publisher'],'prepunct':": ",'prepunctifnolastfield':'. '},
{"fieldsource":['date','year'],'prepunct':", "},
{"fieldsource":['pages'],'prepunct':": "},
{"fieldsource":['urldate'],'prestring':"[","posstring":"]"},
{"fieldsource":['url'],'prepunct':". "},
{"fieldsource":['doi'],'prepunct':". "},
{"fieldsource":['endpunct'],'replstring':"."}
],
"phdthesis":"thesis",
"mastersthesis":"thesis",
}
#
#
#打印格式化后的全部文献条目文本
def printbibliography():
bibliographyentries=bibliographytext.split('\n')
#md文件输出,直接用write写
mdoutfile="newformatted"+inputbibfile.replace('.bib','.md')
fout = open(mdoutfile, 'w', encoding="utf8")
print("INFO: writing cited references to '" + mdoutfile + "'")
biblabelnumber=0
for prtbibentry in bibliographyentries:
if len(prtbibentry)>0:
biblabelnumber=biblabelnumber+1
fout.write('['+str(biblabelnumber)+'] '+prtbibentry+'\n')
fout.close()
#html文件输出,直接用write写
mdoutfile="newformatted"+inputbibfile.replace('.bib','.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>')
biblabelnumber=0
for prtbibentry in bibliographyentries:
if len(prtbibentry)>0:
biblabelnumber=biblabelnumber+1
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()
if auxfile:
bblfile=auxfile.replace('.aux','.bbl')
else:
bblfile=inputbibfile.replace('.bib','.bbl')
bbloutfile=bblfile
fout = open(bbloutfile, 'w', encoding="utf8")
print("INFO: writing cited references to '" + bbloutfile + "'")
fout.write(r'\begin{thebibliography}{'+str(len(bibentries))+'}\n')
biblabelnumber=0
for prtbibentry in bibliographyentries:
if len(prtbibentry)>0:
biblabelnumber=biblabelnumber+1
entrysn=0
for bibentry in bibentries:
entrysn=entrysn+1
if entrysn==biblabelnumber:
entrykeystr=bibentry['entrykey']
entryciteauthor=formatlabelauthor(bibentry)
entryciteyear=formatlabelyear(bibentry)
entrycitelabel=entryciteauthor[0]+'('+entryciteyear+')'+entryciteauthor[1]
#Baker et~al.(1995)Baker and Jackson
break
if formatoptions['style']=='authoryear':
fout.write(r'\bibitem['+entrycitelabel+']{'+entrykeystr+'}'+prtbibentry+'\n')
else:
fout.write(r'\bibitem['+str(biblabelnumber)+']{'+entrykeystr+'}'+prtbibentry+'\n')
fout.write(r'\end{thebibliography}')
fout.close()
#
#authoryear样式提供标注标签的作者信息
#
def formatlabelauthor(bibentry):
if 'author' in bibentry:
namelist=bibentry['author']
elif 'editor' in bibentry:
namelist=bibentry['editor']
elif 'translator' in bibentry:
namelist=bibentry['translator']
else:
namelist='Anon'
return [namelist,namelist]
#
#authoryear样式提供标注标签的年份信息
#
def formatlabelyear(bibentry):
if 'year' in bibentry:
yearlist=bibentry['year']
elif 'eventyear' in bibentry:
yearlist=bibentry['eventyear']
elif 'origyear' in bibentry:
yearlist=bibentry['origyear']
elif 'urlyear' in bibentry:
yearlist=bibentry['urlyear']
else:
yearlist='N.D.'
return yearlist
#
#
#格式化全部文献条目文本
def formatallbibliography():
labelnumber=0
global bibliographytext
bibliographytext=''
for bibentry in bibentries:
labelnumber=labelnumber+1
bibentry['labelnumber']=labelnumber
bibentrytext=''
bibentrytext=formatbibentry(bibentry)
bibliographytext=bibliographytext+bibentrytext+'\n'
print('\nreferecences')
print(bibliographytext)
#
#
#格式化一个文献条目文本
def formatbibentry(bibentry):
print('--------------new entry---------')
print('\nbibentry:',bibentry)
#bibentrytext='entry:'
#
# 由于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]
#四种日期域也做范围解析
if 'date' in bibentry:
if '/' in bibentry['date']:
datestring=bibentry['date'].split('/')
bibentry['date']=datestring[0]
bibentry['enddate']=datestring[1]
if 'urldate' in bibentry:
if '/' in bibentry['urldate']:
datestring=bibentry['urldate'].split('/')
bibentry['urldate']=datestring[0]
bibentry['endurldate']=datestring[1]
if 'eventdate' in bibentry:
if '/' in bibentry['eventdate']:
datestring=bibentry['eventdate'].split('/')
bibentry['eventdate']=datestring[0]
bibentry['endeventdate']=datestring[1]
if 'origdate' in bibentry:
if '/' in bibentry['origdate']:
datestring=bibentry['origdate'].split('/')
bibentry['origdate']=datestring[0]
bibentry['endorigdate']=datestring[1]
#
#接着处理所有域到一个条目文本
#
bibentrytext=''
if bibentry['entrytype'] in bibliographystyle:
print('INFO: format style of entrytype',bibentry['entrytype'],'is defined.')
if isinstance(bibliographystyle[bibentry['entrytype']],str):
formattype=bibliographystyle[bibentry['entrytype']]
else:
formattype=bibentry['entrytype']
lastfield=True #前一域存在
for fieldinfo in bibliographystyle[formattype]:
rtnfield=formatfield(bibentry,fieldinfo,lastfield)
fieldtext=rtnfield[0]
lastfield=rtnfield[1]
bibentrytext=bibentrytext+fieldtext
#对替换字符串做处理
#包括对重复的标点做处理比如:..变为.
for k,v in replacestrings.items():
print(k,v)
#m=re.search(k,bibentrytext)
#print(m)
#bibentrytext=re.sub(k,v,bibentrytext)
#利用正则反而不行,直接用字符串替换
bibentrytext=bibentrytext.replace(k,v)
print(bibentrytext)
return bibentrytext
#
#
#格式化文献条目的域
#不同类型的域不同处理
#分5类:姓名列表,文本列表,文本域,日期域,范围域
#其中姓名列表,文本列表,日期域,日期域,范围域,都需要进行特殊的解析
#而volume,number如果需要特殊解析则在文件域的格式处理时增加新的处理逻辑。
def formatfield(bibentry,fieldinfo,lastfield):
print('fieldinfo:',fieldinfo)
#首先把域的内容先解析处理
fieldcontents=''
fieldsource=None
#首先判断域是否忽略
fieldomit=False
if 'omitifnofield' in fieldinfo and 'omitiffield' in fieldinfo:
fieldomita=True#假设忽略的条件满足
for field in fieldinfo['omitifnofield']:#只要需要不存在的域有一个存在,那么条件就不满足
if field in bibentry:
fieldomita=False
break
fieldomitb=False#假设忽略的条件不满足
for field in fieldinfo['omitiffield']:#只要需要存在的域中有一个存在,那么条件就满足
if field not in bibentry:
fieldomitb=True
break
fieldomit=fieldomita and fieldomitb
elif 'omitifnofield' in fieldinfo:
fieldomit=True#假设忽略的条件满足
for field in fieldinfo['omitifnofield']:#只要需要不存在的域有一个存在,那么条件就不满足
if field in bibentry:
fieldomit=False
break
elif 'omitiffield' in fieldinfo:
fieldomit=False#假设忽略的条件不满足
for field in fieldinfo['omitiffield']:#只要需要存在的域中有一个存在,那么条件就满足
if field not in bibentry:
fieldomit=True
break
print(fieldomit)
#如果不忽略该域那么:
if not fieldomit:
#当域为姓名列表域时:
if fieldinfo['fieldsource'][0] in datatypeinfo['namelist']:
#print('0',fieldinfo['fieldsource'][0])
#print('author' in bibentry)
for field in fieldinfo['fieldsource']:#
#print(fieldinfo['fieldsource'])
#print('namelist:',field)
if field in bibentry:#当域存在域条目中时,确定要处理的域
fieldsource=field
break
if fieldsource:
#传递条目给出的一些控制选项
if 'options' in fieldinfo:
options=fieldinfo['options']
else:
options={}
fieldcontents=namelistparser(bibentry,fieldsource,options)
#当域为文本列表域时:
elif fieldinfo['fieldsource'][0] in datatypeinfo['literallist']:
for field in fieldinfo['fieldsource']:#
if field in bibentry:#当域存在域条目中时,确定要处理的域
fieldsource=field
break
if fieldsource:
fieldcontents=literallistparser(bibentry,fieldsource)
#当域为文本域时:
elif fieldinfo['fieldsource'][0] in datatypeinfo['literalfield']:
for field in fieldinfo['fieldsource']:#
if field in bibentry:#当域存在域条目中时,确定要处理的域
fieldsource=field
break
if fieldsource:
fieldcontents=literalfieldparser(bibentry,fieldsource)
#当域为日期域时:
elif fieldinfo['fieldsource'][0] in datatypeinfo['datefield']:
for field in fieldinfo['fieldsource']:#
if field in bibentry:#当域存在域条目中时,确定要处理的域
fieldsource=field
break
if fieldsource:
#传递条目给出的一些控制选项
if 'options' in fieldinfo:
options=fieldinfo['options']
else:
options={}
fieldcontents=datefieldparser(bibentry,fieldsource,options)
#当域为范围域时:
elif fieldinfo['fieldsource'][0] in datatypeinfo['rangefield']:
for field in fieldinfo['fieldsource']:#
if field in bibentry:#当域存在域条目中时,确定要处理的域
fieldsource=field
break
if fieldsource:
fieldcontents=rangefieldparser(bibentry,fieldsource)
if not fieldsource:
if 'replstring' in fieldinfo and fieldinfo['replstring']:
print('replstring')
fieldsource=True
fieldcontents=fieldinfo['replstring']
#接着做进一步的格式化,包括标点,格式,字体等
fieldtext=''
print(fieldsource)
if fieldsource:
if lastfield:#当前一个著录项存在,则正常输出
if 'prepunct' in fieldinfo:
fieldtext=fieldtext+fieldinfo['prepunct']
else:#当前一个著录项不存在,则首先输出'prepunctifnolastfield'
if 'prepunctifnolastfield' in fieldinfo:
fieldtext=fieldtext+fieldinfo['prepunctifnolastfield']
elif 'prepunct' in fieldinfo:
fieldtext=fieldtext+fieldinfo['prepunct']
if 'prestring' in fieldinfo:
fieldtext=fieldtext+fieldinfo['prestring']
if 'fieldformat' in fieldinfo:
fieldtext=fieldtext+'{'+fieldinfo['fieldformat']+'{'+fieldcontents+'}}'
else:
fieldtext=fieldtext+str(fieldcontents)
if 'posstring' in fieldinfo:
fieldtext=fieldtext+fieldinfo['posstring']
if 'posstringifnumber' in fieldinfo:
try:
numtemp=int(fieldcontents)
if isinstance(numtemp,int):
fieldtext=fieldtext+fieldinfo['posstringifnumber']
except:
print('info:waring the field value can not convert to integer')
if 'pospunct' in fieldinfo:
fieldtext=fieldtext+fieldinfo['pospunct']
#更新lastfiled
lastfield=True
else:
lastfield=False
#自定义标点的处理
print('fieldtext:',fieldtext)
while r'\printdelim' in fieldtext:
m = re.search(r'\\printdelim{([^\}]*)}',fieldtext)#注意贪婪算法的影响,所以要排除\}字符
print('m.group(1):',m.group(1))
fieldtext=re.sub(r'\\printdelim{[^\}]*}',localpuncts[m.group(1)],fieldtext,count=1)
print('fieldtext:',fieldtext)
#本地化字符串的处理
print('fieldtext:',fieldtext)
while r'\bibstring' in fieldtext:
language=languagejudgement(bibentry,fieldinfo,fieldsource)
m = re.search(r'\\bibstring{([^\}]*)}',fieldtext)#注意\字符的匹配,即便是在r''中也需要用\\表示
fieldtext=re.sub(r'\\bibstring{[^\}]*}',localstrings[m.group(1)][language],fieldtext,count=1)
print('fieldtext:',fieldtext)
#下面这句不行因为,在字典取值是,不支持\1这样的正则表达式
#fieldtext=re.sub(r'\\bibstring{(.*)}',localstrings[r'\1'][language],fieldtext,count=1)
#标题的类型和载体标识符的处理
if r'\typestring' in fieldtext:#当需要处理类型和载体时
if bibentry['entrytype'] in typestrings:#当条目对应的类型存在时
print(r'\typestring in',fieldtext)
typestring=typestrings[bibentry['entrytype']]
if 'url' in bibentry:
typestring=typestring.replace(']','/OL]')
elif 'medium' in bibentry:
rplctypestring=bibentry['medium']+']'
typestring=typestring.replace(']',rplctypestring)
else:#当条目对应的类型不存在时,当做其它类型处理
typestring='[Z]'
print(typestring)
fieldtext=fieldtext.replace(r'\typestring',typestring)
return [fieldtext,lastfield]
#
#根据作者域或者标题域确定条目的语言
#
def languagejudgement(bibentry,fieldinfo,fieldsource):
if fieldsource in datatypeinfo['namelist']:#当域是作者类时,利用作者域本身信息做判断
language=fieldlanguage(bibentry[fieldsource])
else:#其它情况,利用title域做判断
if 'title' in bibentry:
language=fieldlanguage(bibentry['title'])
elif 'author' in bibentry:
language=fieldlanguage(bibentry['author'])
else:
language='english'
return language
#
#根据域值所在的字符范围确定域的语言
#
def fieldlanguage(fieldvalueinfo):
if re.match(r'[\u2FF0-\u9FA5]', fieldvalueinfo):
language='chinese'
elif re.match(r'[\u3040-\u30FF\u31F0}-\u31FF]', fieldvalueinfo):
language='japanese'
elif re.match(r'[\u1100-\u11FF\u3130-\u318F\uAC00-\uD7AF]', fieldvalueinfo):
language='korean'
elif re.match(r'[\u0400-\u052F]', fieldvalueinfo):
language='russian'
elif re.match(r'[\u0100-\u017F]', fieldvalueinfo):
language='french'
else:
language='english'
return language
#
#
#对存在{}做保护的字符串进行分割
def safetysplit(strtosplt,seps):
#首先查找{}保护的所有字符串
s1=re.findall('\{.*?\}',strtosplt)
#接着确定保护字符串中是否存在分割用字符串
sepinbrace=False
for s1a in s1:
for sep in seps:
if sep in s1a:
sepinbrace=True
break
if sepinbrace:
break
#print(sepinbrace)
#若保护字符串中存在分割字符串那么做特殊处理
a=strtosplt
if sepinbrace:
#保护字符串用特殊字符串代替,特殊字符串与分割字符串没有任何关联
strsn=0
for stra1 in s1:
strsn=strsn+1
a=a.replace(stra1,'$'+str(strsn)+'$')
#print(a)
#处理原字符串为只需要一个分隔字符串就能分隔
if len(seps)>1:
for i in range(1,len(seps)):
a=a.replace(seps[i],seps[0])
#print(a)
#接着做分割
names=a.split(seps[0])
#print(names)
#对分割后的字符串做还原,即把特殊字符串还原回保护字符串
namesnew=[]
for name in names:
strsn=0
for stra1 in s1:
strsn=strsn+1
name=name.replace('$'+str(strsn)+'$',stra1)
#print(name)
namesnew.append(name.strip().lstrip())
else:
#处理原字符串为只需要一个分隔字符串就能分隔
if len(seps)>1:
for i in range(1,len(seps)):
a=a.replace(seps[i],seps[0])
#print(a)
#直接分割
names=a.split(seps[0])
namesnew=[]
for name in names:
namesnew.append(name.strip().lstrip())
#print(namesnew)
return namesnew
#
#
#姓名列表解析
#增加条目给出的选项
def namelistparser(bibentry,fieldsource,options):
fieldcontents=bibentry[fieldsource]
#首先做针对{}保护的处理
#{}有可能保护一部分,有可能保护全部
#首先判断{}是否存在,若存在,那么可以确定需要做保护处理,否则用常规处理
#当然这些事情可以在一个函数中处理
#首先姓名列表进行分解,包括用' and '和' AND '做分解
#利用safetysplit函数实现安全的分解
seps=[' and ',' AND ']
fieldcontents=fieldcontents.lstrip().strip()
fieldauthors=safetysplit(fieldcontents,seps)
print('fieldauthors:',fieldauthors)
#接着从各个姓名得到更详细的分解信息
fieldnames=[]
for name in fieldauthors:
if name.lower() == 'others':
nameinfo={'morename':True}
else:
if fieldlanguage(name)=='chinese':#当中文姓名中存在逗号先去除
if ', ' in name:
name=name.replace(', ','')
else:
pass
nameinfo=singlenameparser(name)
fieldnames.append(nameinfo)
#最后根据全局和局部选项进行格式化
nameformattedstr=''
#根据'maxbibnames'和'minbibnames'截短
if 'maxbibnames' in options:#首先使用条目中的选项
if len(fieldnames)>options['maxbibnames']:
fieldnamestrunc=fieldnames[:options['minbibnames']]
nameinfo={'morename':True}
fieldnamestrunc.append(nameinfo)
else:
fieldnamestrunc=fieldnames
elif 'maxbibnames' in formatoptions:#接着使用全局选项
if len(fieldnames)>formatoptions['maxbibnames']:
fieldnamestrunc=fieldnames[:formatoptions['minbibnames']]
nameinfo={'morename':True}
fieldnamestrunc.append(nameinfo)
else:
fieldnamestrunc=fieldnames
else:
fieldnamestrunc=fieldnames
#当条目选择中存在'nameformat'
if 'nameformat' in options:
option={'nameformat':options['nameformat']}
else:
option={}
print('fieldnamestrunc:',fieldnamestrunc)
nameliststop=len(fieldnamestrunc)
nameliststart=1
namelistcount=0
for nameinfo in fieldnamestrunc:
namelistcount=namelistcount+1
if 'morename' in nameinfo:
if formatoptions['morenames']:#只有设置morenames为true是才输出other的相关信息
nameformattedstr=nameformattedstr+r'\printdelim{andothorsdelim}\bibstring{andothers}'
else:
if namelistcount==nameliststop and namelistcount>1:#当没有others时最后一个姓名前加的标点
nameformattedstr=nameformattedstr+r'\printdelim{finalnamedelim}'+singlenameformat(nameinfo,option)
elif namelistcount==nameliststart:
nameformattedstr=singlenameformat(nameinfo,option)
else:
nameformattedstr=nameformattedstr+r'\printdelim{multinamedelim}'+singlenameformat(nameinfo,option)
return nameformattedstr
#
#