Skip to content

Instantly share code, notes, and snippets.

@Tomatosoup97
Last active August 20, 2020 11:13
Show Gist options
  • Save Tomatosoup97/f6ae1b96e28e64c35d950967d51df3f2 to your computer and use it in GitHub Desktop.
Save Tomatosoup97/f6ae1b96e28e64c35d950967d51df3f2 to your computer and use it in GitHub Desktop.
Generate bibtex for papers links
#!/usr/bin/env python
"""
Idempotent script for generating bibtex entries for papers from
a given file.
Please note that this script generates a bibtex entry for
each of the supported formats.
Usage: ./generate_bibtex.py <filename>
"""
import sys
import typing as t
# Add more ways to generate bibtex here, for example from doi
get_bibtex_link: t.Dict[str, t.Callable[[str], str]] = {
'dblp': lambda link: f"{link}?view=bibtex",
}
SUPPORTED_FORMATS = get_bibtex_link.keys()
def generate_bibtex(lines: t.List[str]) -> t.Iterator[str]:
for line in lines:
yield line
available_formats = [
link_format for link_format in SUPPORTED_FORMATS
if f'[{link_format}]' in line
]
if len(available_formats) == 0:
continue
link_format = available_formats[0]
link = line[10:-3]
bibtex_link = get_bibtex_link[link_format](link)
# guarantee idempotency
bibtex_present = any(bibtex_link in line for line in lines)
if not bibtex_present:
yield f" ([bibtex]({bibtex_link}))\n"
def main(filename):
with open(filename) as f:
lines = f.readlines()
with open(filename, "w") as f:
f.write(''.join(generate_bibtex(lines)))
if __name__ == "__main__":
filename = sys.argv[1]
main(filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment