Skip to content

Instantly share code, notes, and snippets.

@mikeesto
Created March 29, 2023 23:22
Show Gist options
  • Save mikeesto/764afc1daeed449a8c9332aeffef016f to your computer and use it in GitHub Desktop.
Save mikeesto/764afc1daeed449a8c9332aeffef016f to your computer and use it in GitHub Desktop.
Convert CSV file to BibTeX
import csv
def generate_bibtex_key(authors, year):
"""Generate a BibTeX key from the first author's last name and the year"""
last_names = authors.split(",")[0].split()
last_name = last_names[-1] if len(last_names) > 0 else ""
return f"{last_name.lower()}{year}"
def convert_csv_to_bibtex(csv_file, bibtex_file):
"""Convert a CSV file to BibTeX format"""
with open(csv_file, newline="", encoding="utf-8-sig") as csvfile:
reader = csv.DictReader(csvfile)
with open(bibtex_file, "w", encoding="utf-8") as bibtexfile:
for row in reader:
authors = row["Authors"]
year = row["Year"]
title = row["Title"]
source_title = row["Source title"]
volume = row["Volume"]
pages = f"{row['Page start']}-{row['Page end']}"
doi = row["DOI"]
# bibtex_key = generate_bibtex_key(authors, year)
bibtex_entry = f"@article{{\n" \
f" author = {{{authors}}},\n" \
f" title = {{{title}}},\n" \
f" year = {{{year}}},\n" \
f" number = 1,\n" \
f" journal = {{{source_title}}},\n" \
f" volume = {{{volume}}},\n" \
f" pages = {{{pages}}},\n" \
f" doi = {{{doi}}}\n" \
f"}}\n\n"
bibtexfile.write(bibtex_entry)
# Example usage
convert_csv_to_bibtex("scopus.csv", "scopus.bib")
@CrausMiguel
Copy link

CrausMiguel commented Dec 4, 2023

Hello Mikeesto
May i ask what is the template of csv used as base for this ?
I have a csv file where i use a twos columns and one row to each info so i get an error in the 17 line
Ex:
[Row 1 [Info Column 1] [Info Column 2]]
[Row 2 [Info Column 1] [Info Column 2]]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment