-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetbibs
More file actions
executable file
·46 lines (41 loc) · 1.9 KB
/
getbibs
File metadata and controls
executable file
·46 lines (41 loc) · 1.9 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
#!/usr/bin/env python3
import argparse
import sys
"""
Extract all bibtex references from a plaintext document
"""
if __name__ == "__main__":
# parse input arguments
parser = argparse.ArgumentParser(description="Extract all bibtex-formatted references from a plaintext document.")
parser.add_argument("-i", "--infile", type=str, default=None, help="File from which to extract references, default stdin")
parser.add_argument("-o", "--output", type=str, default=None, help="Output file to save references to, default stdout")
parser.add_argument("-r", "--remove", action="store_true", default=False, help="Instead of producing references file, produce file with references removed")
args=parser.parse_args()
reference_lines = []
text_lines = []
# Open text file for processing
with (open(args.infile, 'r') if args.infile else sys.stdin) as infile:
line = infile.readline()
while line:
# If a line doesn't start with '@', ignore it
if not line.lstrip().startswith('@'):
text_lines.append(line)
line = infile.readline()
continue
# Otherwise, start recording a new reference
this_ref = []
running_total = line.count('{') - line.count('}')
# While the reference is open, and EOF not reached...
while running_total>0 and line:
this_ref.append(line)
line = infile.readline()
running_total += (line.count('{') - line.count('}'))
# Either reference is closed, or EOF reached
reference_lines += ( this_ref + ['}\n\n'])
line = infile.readline()
output_lines = text_lines if args.remove else reference_lines
if args.output is None:
print(''.join(output_lines))
else:
with open(args.output, 'w') as outfile:
outfile.write(''.join(output_lines))