-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformatter.py
More file actions
523 lines (413 loc) · 15.5 KB
/
formatter.py
File metadata and controls
523 lines (413 loc) · 15.5 KB
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
"""
格式化核心模块
解析 BibTeX,并根据选定样式(如 GB/T 7714)生成目标格式的引用字符串。
"""
import bibtexparser
from bibtexparser.bparser import BibTexParser
from bibtexparser.customization import convert_to_unicode
# 定义格式样式字典
FORMAT_STYLES = {
"GBT2015": "GB/T 7714-2015 (期刊,3作者后加 et al.)",
"GBT2005": "GB/T 7714-2005 (期刊,全作者或简写规则不同)",
"APA": "APA 7th Edition",
"IEEE": "IEEE Standard"
}
def format_bibtex_to_style(index, bibtex_string, target_style, key_info=None, confidence=None, warning=None):
"""
将 BibTeX 字符串格式化为指定样式,并包含置信度信息。
参数:
index (int): 文献序号
bibtex_string (str): BibTeX 格式字符串
target_style (str): 目标格式样式代码(如 "GBT2015")
key_info (dict): 从输入中提取的关键信息,用于验证和修正卷期页
confidence (float): 置信度评分 (0.0-1.0),如果提供则显示在输出中
warning (str): 缺项警告字符串,如果提供则显示在输出中
返回:
str: 格式化后的引用字符串,包含置信度信息
"""
if not bibtex_string:
return f"[{index}] 无法格式化:BibTeX 数据为空"
try:
# 解析 BibTeX
parser = BibTexParser()
parser.customization = convert_to_unicode
bib_database = bibtexparser.loads(bibtex_string, parser=parser)
if not bib_database.entries:
return f"[{index}] 无法格式化:BibTeX 解析失败"
entry = bib_database.entries[0]
# 如果输入包含卷期页信息,进行验证和修正
if key_info:
# 检查并修正卷期页信息
if key_info.get('volume') and not entry.get('volume'):
entry['volume'] = key_info['volume']
print(f" ⚠ 使用输入中的卷号: {key_info['volume']}")
elif key_info.get('volume') and entry.get('volume') != key_info['volume']:
print(f" ⚠ 卷号不匹配 - 检索: {entry.get('volume')}, 输入: {key_info['volume']}")
# 使用输入中的卷号(更可靠)
entry['volume'] = key_info['volume']
if key_info.get('number') and not entry.get('number'):
entry['number'] = key_info['number']
print(f" ⚠ 使用输入中的期号: {key_info['number']}")
elif key_info.get('number') and entry.get('number') != key_info['number']:
print(f" ⚠ 期号不匹配 - 检索: {entry.get('number')}, 输入: {key_info['number']}")
entry['number'] = key_info['number']
if key_info.get('pages') and not entry.get('pages'):
entry['pages'] = key_info['pages']
print(f" ⚠ 使用输入中的页码: {key_info['pages']}")
elif key_info.get('pages') and entry.get('pages') != key_info['pages']:
print(f" ⚠ 页码不匹配 - 检索: {entry.get('pages')}, 输入: {key_info['pages']}")
# 使用输入中的页码(更可靠)
entry['pages'] = key_info['pages']
# 根据样式格式化
if target_style == "GBT2015":
formatted_text = format_gbt2015(index, entry)
elif target_style == "GBT2005":
formatted_text = format_gbt2005(index, entry)
elif target_style == "APA":
formatted_text = format_apa(index, entry)
elif target_style == "IEEE":
formatted_text = format_ieee(index, entry)
else:
formatted_text = f"[{index}] 未知格式样式:{target_style}"
# 添加置信度信息
if confidence is not None and warning is not None:
confidence_str = f"{confidence:.2f}"
confidence_info = f" (置信度: {confidence_str}, {warning})"
formatted_text += confidence_info
return formatted_text
except Exception as e:
error_msg = f"[{index}] 格式化错误:{e}"
if confidence is not None and warning is not None:
error_msg += f" (置信度: {confidence:.2f}, {warning})"
return error_msg
def format_gbt2015(index, entry):
"""
格式化为 GB/T 7714-2015 标准。
格式:作者. 题名[J]. 刊名, 年, 卷(期):页码.
"""
# 提取作者
authors = entry.get('author', '').split(' and ')
author_str = format_authors_gbt(authors, max_authors=3)
# 提取题名
title = entry.get('title', '').strip('{}')
# 文献类型标识
entry_type = entry.get('ENTRYTYPE', 'article')
type_marker = '[J]' if entry_type == 'article' else '[M]'
# 提取刊名
journal = entry.get('journal', entry.get('booktitle', '')).strip('{}')
# 提取年份
year = entry.get('year', '')
# 提取卷
volume = entry.get('volume', '')
# 提取期
number = entry.get('number', entry.get('issue', ''))
# 提取页码
pages = entry.get('pages', '').replace('--', '-')
# 构建引用字符串
# GB/T 7714-2015 格式:作者. 题名[J]. 刊名, 年, 卷(期):页码.
# 题名和文献类型标识(题名和[J]之间没有点号)
title_marker = ''
if title:
title_marker = f"{title}{type_marker}" # 题名和[J]直接连接,无点号
else:
title_marker = type_marker
# 构建前半部分:作者. 题名[J]. 刊名
front_parts = []
if author_str:
front_parts.append(author_str)
front_parts.append(title_marker)
if journal:
front_parts.append(journal)
front_part = '. '.join(front_parts)
# 构建后半部分:年, 卷(期):页码
back_parts = []
if year:
back_parts.append(year)
# 卷(期)部分
volume_part = ''
if volume:
if number:
volume_part = f"{volume}({number})"
else:
volume_part = volume
elif number:
volume_part = f"({number})"
# 页码部分
if pages:
if volume_part:
# 卷(期)后直接跟冒号和页码
back_parts.append(f"{volume_part}:{pages}")
else:
# 只有页码,年份后直接跟冒号和页码
back_parts.append(f":{pages}")
elif volume_part:
back_parts.append(volume_part)
# 连接后半部分(用逗号分隔年份和卷(期))
if back_parts:
back_part = ', '.join(back_parts)
result = f"{front_part}, {back_part}."
else:
result = f"{front_part}."
return f"[{index}] {result}"
def format_gbt2005(index, entry):
"""
格式化为 GB/T 7714-2005 标准。
与 2015 版本类似,但作者处理规则可能不同。
"""
# 提取作者(2005版本可能显示更多作者)
authors = entry.get('author', '').split(' and ')
author_str = format_authors_gbt(authors, max_authors=5) # 2005版本可能显示更多作者
# 提取题名
title = entry.get('title', '').strip('{}')
# 文献类型标识
entry_type = entry.get('ENTRYTYPE', 'article')
type_marker = '[J]' if entry_type == 'article' else '[M]'
# 提取刊名
journal = entry.get('journal', entry.get('booktitle', '')).strip('{}')
# 提取年份
year = entry.get('year', '')
# 提取卷
volume = entry.get('volume', '')
# 提取期
number = entry.get('number', entry.get('issue', ''))
# 提取页码
pages = entry.get('pages', '').replace('--', '-')
# 构建引用字符串
# GB/T 7714-2005 格式:作者. 题名[J]. 刊名, 年, 卷(期):页码.
result_parts = []
# 作者部分
if author_str:
result_parts.append(author_str)
# 题名和文献类型标识(题名和[J]之间没有点号)
title_marker = ''
if title:
title_marker = f"{title}{type_marker}" # 题名和[J]直接连接,无点号
else:
title_marker = type_marker
# 构建前半部分:作者. 题名[J]. 刊名
front_parts = []
if author_str:
front_parts.append(author_str)
front_parts.append(title_marker)
if journal:
front_parts.append(journal)
front_part = '. '.join(front_parts)
# 构建后半部分:年, 卷(期):页码
back_parts = []
if year:
back_parts.append(year)
# 卷(期)部分
volume_part = ''
if volume:
if number:
volume_part = f"{volume}({number})"
else:
volume_part = volume
elif number:
volume_part = f"({number})"
# 页码部分
if pages:
if volume_part:
# 卷(期)后直接跟冒号和页码
back_parts.append(f"{volume_part}:{pages}")
else:
# 只有页码,年份后直接跟冒号和页码
back_parts.append(f":{pages}")
elif volume_part:
back_parts.append(volume_part)
# 连接后半部分(用逗号分隔年份和卷(期))
if back_parts:
back_part = ', '.join(back_parts)
result = f"{front_part}, {back_part}."
else:
result = f"{front_part}."
return f"[{index}] {result}"
def format_apa(index, entry):
"""
格式化为 APA 7th Edition 标准。
格式:Author, A. A., & Author, B. B. (Year). Title. Journal Name, Volume(Issue), Pages.
"""
# 提取作者
authors = entry.get('author', '').split(' and ')
author_str = format_authors_apa(authors)
# 提取年份
year = entry.get('year', '')
# 提取题名
title = entry.get('title', '').strip('{}')
# 提取刊名
journal = entry.get('journal', entry.get('booktitle', '')).strip('{}')
# 提取卷
volume = entry.get('volume', '')
# 提取期
number = entry.get('number', entry.get('issue', ''))
# 提取页码
pages = entry.get('pages', '').replace('--', '-')
# 构建引用字符串
parts = []
if author_str:
parts.append(author_str)
if year:
parts.append(f"({year})")
if title:
parts.append(title)
# 期刊信息
journal_info = []
if journal:
journal_info.append(journal)
if volume:
if number:
journal_info.append(f"{volume}({number})")
else:
journal_info.append(volume)
elif number:
journal_info.append(f"({number})")
if journal_info:
parts.append(', '.join(journal_info))
if pages:
parts.append(pages)
result = '. '.join(parts)
if not result.endswith('.'):
result += '.'
return f"[{index}] {result}"
def format_ieee(index, entry):
"""
格式化为 IEEE 标准。
格式:A. Author, B. Author, and C. Author, "Title," Journal Name, vol. X, no. Y, pp. Z, Year.
"""
# 提取作者
authors = entry.get('author', '').split(' and ')
author_str = format_authors_ieee(authors)
# 提取题名
title = entry.get('title', '').strip('{}')
# 提取刊名
journal = entry.get('journal', entry.get('booktitle', '')).strip('{}')
# 提取卷
volume = entry.get('volume', '')
# 提取期
number = entry.get('number', entry.get('issue', ''))
# 提取页码
pages = entry.get('pages', '').replace('--', '-')
# 提取年份
year = entry.get('year', '')
# 构建引用字符串
parts = []
if author_str:
parts.append(author_str)
if title:
parts.append(f'"{title}"')
if journal:
parts.append(journal + ',')
if volume:
parts.append(f'vol. {volume}')
if number:
parts.append(f'no. {number}')
if pages:
parts.append(f'pp. {pages}')
if year:
parts.append(year)
result = ', '.join(parts)
if not result.endswith('.'):
result += '.'
return f"[{index}] {result}"
def format_authors_gbt(authors, max_authors=3):
"""
格式化作者列表为 GB/T 格式。
超过 max_authors 位作者时,只显示前 max_authors 位,然后加 et al.
"""
if not authors:
return ''
# 清理作者名称
cleaned_authors = []
for author in authors:
author = author.strip()
if author:
# 处理 "Family, Given" 格式
if ',' in author:
parts = author.split(',', 1)
family = parts[0].strip()
given = parts[1].strip() if len(parts) > 1 else ''
# GB/T 格式:姓 名(名缩写,空格分隔,无点号)
if given:
# 提取首字母,空格分隔,无点号
initials = ' '.join([n[0].upper() for n in given.split() if n])
cleaned_authors.append(f"{family} {initials}")
else:
cleaned_authors.append(family)
else:
cleaned_authors.append(author)
if not cleaned_authors:
return ''
# 如果作者数量超过限制,只显示前几位,然后加 et al.
if len(cleaned_authors) > max_authors:
displayed = cleaned_authors[:max_authors]
return ', '.join(displayed) + ', et al'
else:
return ', '.join(cleaned_authors)
def format_authors_apa(authors):
"""
格式化作者列表为 APA 格式。
"""
if not authors:
return ''
formatted = []
for i, author in enumerate(authors):
author = author.strip()
if not author:
continue
if ',' in author:
# "Family, Given" 格式
parts = author.split(',', 1)
family = parts[0].strip()
given = parts[1].strip() if len(parts) > 1 else ''
if given:
# 提取首字母
initials = ' '.join([n[0].upper() + '.' for n in given.split() if n])
formatted.append(f"{family}, {initials}")
else:
formatted.append(family)
else:
formatted.append(author)
if not formatted:
return ''
if len(formatted) == 1:
return formatted[0]
elif len(formatted) == 2:
return f"{formatted[0]} & {formatted[1]}"
else:
last = formatted[-1]
others = ', '.join(formatted[:-1])
return f"{others}, & {last}"
def format_authors_ieee(authors):
"""
格式化作者列表为 IEEE 格式。
"""
if not authors:
return ''
formatted = []
for author in authors:
author = author.strip()
if not author:
continue
if ',' in author:
# "Family, Given" 格式转换为 "G. Family" 格式
parts = author.split(',', 1)
family = parts[0].strip()
given = parts[1].strip() if len(parts) > 1 else ''
if given:
# 提取首字母
initials = '. '.join([n[0].upper() for n in given.split() if n])
formatted.append(f"{initials}. {family}")
else:
formatted.append(family)
else:
formatted.append(author)
if not formatted:
return ''
if len(formatted) == 1:
return formatted[0]
elif len(formatted) == 2:
return f"{formatted[0]} and {formatted[1]}"
else:
last = formatted[-1]
others = ', '.join(formatted[:-1])
return f"{others}, and {last}"