Pybtex: BibTeX-compatible bibliography processor

0.26.1 · active · verified Sat Apr 11

Pybtex is a BibTeX-compatible bibliography processor written in Python, designed to read citation information from various formats (BibTeX, BibTeXML, YAML) and produce formatted bibliographies. It supports traditional BibTeX `.bst` styles and also allows for defining custom styles directly in Python, with output options including LaTeX, HTML, Markdown, or plain text. Currently at version 0.26.1, it is actively maintained and serves as a flexible alternative or drop-in replacement for the original BibTeX.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to parse a BibTeX file, apply a predefined formatting style (or a custom one), and output the result to an HTML file using Pybtex's Python API. It creates a dummy `.bib` file, processes it, and then cleans up the generated files. For more complex use cases, especially with `.aux` files, the command-line interface or the `pybtex.Engine` might be more suitable.

from pybtex.database.input import bibtex
from pybtex.database.output import html
from pybtex.style.formatting import plain
from pybtex.style.template import field, sentence, tag
import os

# Create a dummy .bib file for demonstration
bib_content = """
@article{einstein1905relativity,
  title={Zur Elektrodynamik bewegter K\"orper},
  author={Einstein, Albert},
  journal={Annalen der Physik},
  volume={322},
  number={10},
  pages={891-921},
  year={1905},
  doi={10.1002/andp.19053221006}
}
"""
with open('references.bib', 'w') as f:
    f.write(bib_content)

# 1. Parse the bibliography data
parser = bibtex.Parser()
bib_data = parser.parse_file('references.bib')

# 2. Select a formatting style (e.g., 'plain' or a custom one)
# For a custom style, you would inherit from BaseStyle
style = plain.Style()

# 3. Format the bibliography
# The 'citations' argument specifies which entries to include. 
# If not provided, all entries in bib_data will be formatted.
formatted_bibliography = style.format_bibliography(bib_data, citations=['einstein1905relativity'])

# 4. Write the formatted bibliography to an output file (e.g., HTML)
writer = html.Writer()
with open('output.html', 'w') as f:
    writer.write_file(formatted_bibliography, f)

print("Bibliography processed and saved to output.html")

# Clean up dummy file
os.remove('references.bib')
os.remove('output.html')

view raw JSON →