-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbibtex_prettifier.rb
More file actions
62 lines (51 loc) · 1.24 KB
/
bibtex_prettifier.rb
File metadata and controls
62 lines (51 loc) · 1.24 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
require 'bibtex'
# Remove 'url' if 'doi' is present
def remove_redundant_url(bib)
bib.each do |entry|
if entry.has_field?('doi') && entry.has_field?('url')
entry.delete('url')
end
end
end
def normalize_doi(doi)
doi.to_s.strip.downcase
end
def normalize_title(title)
title.to_s
.gsub(/[{}]/, '') # remove braces
.downcase
.gsub(/\s+/, ' ') # collapse whitespace
.strip
end
def remove_duplicates(bib)
seen_dois = {}
seen_titles = {}
duplicates = []
bib.each do |entry|
doi = normalize_doi(entry['doi'])
title = normalize_title(entry['title'])
if !doi.empty?
if seen_dois.key?(doi)
duplicates << entry
else
seen_dois[doi] = entry
end
elsif !title.empty?
if seen_titles.key?(title)
duplicates << entry
else
seen_titles[title] = entry
end
end
end
duplicates.each { |entry| bib.delete(entry) }
end
# Load BibTeX
bibfile = "bibliography.bib"
bib = BibTeX.open(bibfile)
remove_redundant_url(bib)
remove_duplicates(bib)
# Overwrite the original file
output_file = "bibliography.bib"
File.open(output_file, 'w') { |f| f.write(bib.to_s) }
puts "BibTeX file #{output_file} has been updated (duplicates removed)"