### Install from Source Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/docs/source/install.md Install the library by downloading the source code from GitHub and running pip install in the project's root directory. This installs the stable version. ```sh pip install . ``` -------------------------------- ### Install Development Version from GitHub Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/docs/source/install.md Use this command to install the latest development version directly from the main branch of the GitHub repository. Ensure you have pip installed. ```sh pip install --no-cache-dir --force-reinstall git+https://github.com/sciunto-org/python-bibtexparser@main ``` -------------------------------- ### Install Latest Release Candidate from PyPI Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/docs/source/install.md Install the latest release candidate (v2) using pip with the --pre flag. Omitting --pre installs the latest v1 version, which has a different API. ```sh pip install --pre bibtexparser ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/CONTRIBUTING.md Installs the necessary development dependencies for testing and documentation for the v2 branch. ```bash pip install -e .[test,docs] ``` -------------------------------- ### Install from Source with Dev Dependencies Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/docs/source/install.md Install the library from source while also including development dependencies for testing, linting, and documentation. This requires downloading the source code first. ```sh pip install .[test,lint,docs] ``` -------------------------------- ### Install Bibtexparser v2 (Pre-release) Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/README.md Install the latest pre-release version of bibtexparser v2 using pip. ```bash pip install bibtexparser --pre ``` -------------------------------- ### Install Bibtexparser v1 Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/README.md Install version 1.x of bibtexparser using pip. Note that v2 is recommended for new projects. ```bash pip install bibtexparser~=1.0 ``` -------------------------------- ### Basic Block Middleware Example Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/docs/source/customize.md Extend `BlockMiddleware` to perform transformations on individual BibTeX entries. This example converts the 'title' field to lowercase. ```python from bibtexparser.middlewares import BlockMiddleware class MyMiddleware(BlockMiddleware): def transform_entry(self, entry, *args, **kwargs): # Do something with the entry, e.g. entry["title"] = entry["title"].lower() # Return the transformed entry return entry ``` -------------------------------- ### Lint Code Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/CONTRIBUTING.md Enforces code style guidelines using pre-commit. Install pre-commit with 'pip install pre-commit' if needed. ```bash pre-commit run --all-files ``` -------------------------------- ### Format and Write BibTeX String Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/examples/middelware.ipynb Customize the formatting of a BibTeX library before writing it to a string. This example sets custom indentation and block separators. ```python bibtex_format = bibtexparser.BibtexFormat() bibtex_format.indent = ' ' bibtex_format.block_separator = '\n\n' bib_str = bibtexparser.write_string(library, bibtex_format=bibtex_format) print(bib_str) ``` -------------------------------- ### Parse BibTeX File with Custom Middleware Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/examples/middelware.ipynb Parse a BibTeX file and append custom middleware layers to the parsing process. This example uses MonthIntMiddleware, SeparateCoAuthors, and SplitNameParts to modify how month, co-authors, and name parts are handled. ```python import bibtexparser.middlewares as m # We want to add three new middleware layers to our parse stack: layers = [ m.MonthIntMiddleware(), # Months should be represented as int (0-12) m.SeparateCoAuthors(), # Co-authors should be separated m.SplitNameParts() # Names should be split into first, von, last, jr parts ] library_append_pstack = bibtexparser.parse_file('bibtex.bib', append_middleware=layers) print(library_append_pstack.entries[0]) ``` -------------------------------- ### Export BibTeX to String or File Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/docs/source/quickstart.md Use `write_string` to get the BibTeX content as a string or `write_file` to save it to a file. The output closely matches the original format. ```python new_bibtex_str = bibtexparser.write_string(library) # or bibtexparser.write_file("my_new_file.bib", library) print(new_bibtex_str) # Output: # @comment{This is my example comment.} # # # @article{Cesar2013, # author = {Jean César}, # title = {An amazing title}, # year = {2013}, # volume = {12}, # pages = {12--23}, # journal = {Nice Journal} # } ``` -------------------------------- ### Sort BibTeX Entries by Year Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/docs/source/customize.md Use `SortBlocksMiddleware` with a custom key function to sort BibTeX entries by year. This example demonstrates how to define a `by_year` function that handles different block types and sorts entries numerically by year, with ties broken by citation key. ```python import bibtexparser import bibtexparser.middlewares as m from bibtexparser.model import Entry def by_year(block): # Tuple sort keys allow sorting libraries with mixed block types: # Non-entries (e.g. @string) and entries without a year are put on top, # remaining entries are sorted by year, ties broken by citation key. if isinstance(block, Entry) and "year" in block: return (1, int(block["year"]), block.key) return (0, 0, "") library = bibtexparser.parse_file("bibtex.bib") bibtexparser.write_file( "sorted.bib", library, prepend_middleware=[m.SortBlocksMiddleware(key=by_year)] ) ``` -------------------------------- ### Block Middleware Overriding Default Arguments Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/docs/source/customize.md Customize default middleware arguments like `allow_parallel_execution` and `allow_inplace_modification` by specifying them in the `super().__init__()` call. This example disables both parallel execution and in-place modification. ```python from bibtexparser.middlewares import BlockMiddleware class MyMiddleware(BlockMiddleware): def __init__(self, my_param): self.my_param = my_param super().__init__( allow_parallel_execution = False, allow_inplace_modification = False, ) def transform_entry(self, entry, *args, **kwargs): # Do something with the entry, e.g. entry["title"] = entry["title"].lower() # Return the transformed entry return entry ``` -------------------------------- ### Access Details of a Failed BibTeX Block Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/docs/source/quickstart.md When a BibTeX block fails to parse, you can access attributes of the `ParsingFailedBlock` object to investigate the error. These include the exception, the starting line number, and the raw BibTeX content. ```python failed_block = library.failed_blocks[0] failed_block.error # The exception describing why parsing failed failed_block.start_line # The line in the file where the block started failed_block.raw # The raw, unparsed bibtex of the block ``` -------------------------------- ### Build and Preview Documentation Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/CONTRIBUTING.md Builds the project documentation and makes it available for preview. Navigate to the 'docs' directory first. ```bash make html ``` -------------------------------- ### Block Middleware with Initialization Parameters Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/docs/source/customize.md Initialize a custom `BlockMiddleware` with parameters. The `__init__` method can accept arguments, which are stored and can be used within transformation methods. ```python from bibtexparser.middlewares import BlockMiddleware class MyMiddleware(BlockMiddleware): def __init__(self, my_param): self.my_param = my_param super().__init__() def transform_entry(self, entry, *args, **kwargs): # Do something with the entry, e.g. entry["title"] = entry["title"].lower() # Return the transformed entry return entry ``` -------------------------------- ### Change Entrypoint from v1 to v2 Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/docs/source/migrate.md Illustrates the change in the primary package entrypoint for loading a bibtex file between v1 and v2. Default settings are used, but customization is possible via documentation. ```python # v1 import bibtexparser with open('bibtex.bib') as bibtex_file: bib_database = bibtexparser.load(bibtex_file) # v2 import bibtexparser library = bibtexparser.parse_file(bibtex_file) ``` -------------------------------- ### Accessing Entries in v1 vs v2 Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/docs/source/migrate.md Demonstrates how to access entry titles, showing the v1 dictionary-based access and the v2 object-oriented approach with both direct field access and a shorthand notation for migration. ```python # v1 for entry in bib_database.entries: print(entry['title']) # v2 for entry in library.entries: # ... the new 'typed' way to access fields values ... print(entry.fields_dict['title'].value) # ... but to facilitate migration or simple cases, this shorthand notation also works ... print(entry['title']) ``` -------------------------------- ### Run Tests Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/CONTRIBUTING.md Executes the test suite to ensure code quality and functionality for the v2 branch. ```bash pytest . ``` -------------------------------- ### Import Bibtexparser Library Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/examples/middelware.ipynb Import the main bibtexparser library to begin parsing BibTeX files. ```python import bibtexparser ``` -------------------------------- ### Control Value Enclosure with Middleware Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/docs/source/customize.md Demonstrates how `MonthAbbreviationMiddleware` influences value enclosure. Values that must not be enclosed, like month abbreviations, are written without braces or quotes. ```python library = bibtexparser.parse_string('@article{k, month = {1}, year = {2000}}') bib_str = bibtexparser.write_string( library, prepend_middleware=[bibtexparser.middlewares.MonthAbbreviationMiddleware()] ) # The month abbreviation middleware demands `month.enclosing = "no-enclosing"`, # hence the written entry contains `month = jan` (a string reference) # and not `month = {jan}` (a literal). ``` -------------------------------- ### Access Specific Comment and Entry Details Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/examples/quickstart.ipynb Access and print details of the first comment and the first entry from the parsed library. Demonstrates accessing specific attributes like `comment`, `key`, `entry_type`, and `fields_dict`. ```python first_comment = library.comments[0] print(f"The Comment is of type {type(first_comment)}, exposing amongst others the following attributes:") print(f" - `block.comment` to get the parsed comment: '{first_comment.comment}' ") first_entry = library.entries[0] print(f""" The Entry is of type {type(first_entry)}, exposing amongst others the following attributes:" - `entry.key` to get the parsed key: '{first_entry.key}' " - `entry.type` to get the parsed type: '{first_entry.entry_type}' " - `entry.fields` and `entry.fields_dict` to get the parsed fields (e.g. for author, journal, ...), as a list of `Field` objects:' " - e.g. `entry.fields_dict['author'].value` to get '{first_entry.fields_dict['author'].value}' " - e.g. `entry.fields[2].key` to get the key of the 3rd field '{first_entry.fields[2].key}' """ ``` -------------------------------- ### Basic Bibtex Parsing and Writing Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/README.md Parse a bibtex string into a database object and convert it back to a string using default settings. ```python # Parsing a bibtex string with default values bib_database = bibtexparser.parse_string(bibtex_string) # Converting it back to a bibtex string, again with default values new_bibtex_string = bibtexparser.write_string(bib_database) ``` -------------------------------- ### Parse BibTeX File with Default Settings Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/examples/middelware.ipynb Parse a BibTeX file using the default middleware stack. This will process the file and store entries in a library object. ```python library = bibtexparser.parse_file('bibtex.bib') print(library.entries[0]) ``` -------------------------------- ### Manually Set Field Enclosure Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/docs/source/customize.md Shows how to manually enforce a specific enclosure type (e.g., quotes) for a particular field by setting its `enclosing` attribute. Assigning a new value resets `enclosing` to `None`. ```python entry.fields_dict["title"].enclosing = '"' ``` -------------------------------- ### Define BibTeX String Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/examples/quickstart.ipynb Define a multi-line string containing BibTeX formatted data, including comments and entries. ```python bibtex_str = """ @comment{ This is my example comment. } @ARTICLE{Cesar2013, author = {Jean César}, title = {An amazing title}, year = {2013}, volume = {12}, pages = {12--23}, journal = {Nice Journal} } """ ``` -------------------------------- ### Advanced Bibtex Parsing with Middleware Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/README.md Parse a bibtex string using custom middleware to split authors and name parts. This allows for more detailed entry processing. ```python # Lets parse some bibtex string. bib_database = bibtexparser.parse_string(bibtex_string, # Middleware layers to transform parsed entries. # Here, we split multiple authors from each other and then extract first name, last name, ... for each append_middleware=[SeparateCoAuthors(), SplitNameParts()]), # Here you have a `bib_database` with all parsed bibtex blocks. # Let's transform it back to a bibtex_string. new_bibtex_string = bibtexparser.write_string(bib_database, # Revert above transformation prepend_middleware=[MergeNameParts(), MergeCoAuthors()]) ``` -------------------------------- ### Access Entry Attributes Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/docs/source/quickstart.md Retrieves key, type, and fields from a parsed entry block. Fields can be accessed as a list of Field objects or a dictionary. ```python # Entries have more attributes first_entry = library.entries[0] first_entry.key # The entry key first_entry.entry_type # The entry type, e.g. "article" first_entry.fields # The entry fields (e.g. author, title, etc. with their values) first_entry.fields_dict # The entry fields, as a dictionary by field key ``` -------------------------------- ### Access Parsed Blocks Count Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/docs/source/quickstart.md Prints the total number of blocks parsed and the counts for entries, comments, strings, and preambles. ```python print(f"Parsed {len(library.blocks)} blocks, including:" f"\n\t{len(library.entries)} entries" f"\n\t{len(library.comments)} comments" f"\n\t{len(library.strings)} strings and" f"\n\t{len(library.preambles)} preambles") ``` -------------------------------- ### Adding Custom Middleware Layers to Parse Stack Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/docs/source/customize.md This snippet demonstrates how to append custom middleware layers to the default parse stack. Use this when you need to apply specific transformations like converting months to integers, separating co-authors, or splitting name parts. ```python import bibtexparser.middlewares as m # We want to add three new middleware layers to our parse stack: layers = [ m.MonthIntMiddleware(), # Months should be represented as int (0-12) m.SeparateCoAuthors(), # Co-authors should be separated as list of strings m.SplitNameParts() # Individual Names should be split into first, von, last, jr parts ] library = bibtexparser.parse_file('bibtex.bib', append_middleware=layers) ``` -------------------------------- ### Access Field Attributes Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/docs/source/quickstart.md Retrieves the key and value from a specific field within a parsed entry. ```python # Each field of the entry is a `bibtexparser.model.Field` instance first_field = first_entry.fields[0] first_field.key # The field key, e.g. "author" first_field.value # The field value, e.g. "Albert Einstein and Boris Johnson" ``` -------------------------------- ### Check for Failed BibTeX Blocks Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/docs/source/quickstart.md After parsing a BibTeX file, check the `library.failed_blocks` list to see if any blocks failed to parse. This helps ensure no errors go unnoticed. ```python if len(library.failed_blocks) > 0: print("Some blocks failed to parse. Check the entries of `library.failed_blocks`.") else: print("All blocks parsed successfully") ``` -------------------------------- ### Access Parsed Blocks Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/examples/quickstart.ipynb Print the count of different types of parsed blocks (entries, comments, strings, preambles) from the library object. ```python print(f"Parsed {len(library.blocks)} blocks, including:" f"\n\t{len(library.entries)} entries" f"\n\t{len(library.comments)} comments" f"\n\t{len(library.strings)} strings and" f"\n\t{len(library.preambles)} preambles") ``` -------------------------------- ### Write BibTeX Library to String Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/examples/quickstart.ipynb Write the parsed BibTeX library object back into a BibTeX formatted string. This is useful for modifying and saving BibTeX data. ```python library = bibtexparser.parse_string(bibtex_str) new_bibtex_str = bibtexparser.write_string(library) print(new_bibtex_str) ``` -------------------------------- ### Check for Failed Blocks Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/examples/quickstart.ipynb Check if any blocks failed to parse and print a message indicating success or failure. This helps in identifying potential issues with the BibTeX input. ```python if len(library.failed_blocks) > 0: print("Some blocks failed to parse. Check the entries of `library.failed_blocks` for more details") else: print("All blocks parsed successfully") ``` -------------------------------- ### Parse BibTeX String Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/examples/quickstart.ipynb Parse a BibTeX formatted string into a library object. Alternatively, use `bibtexparser.parse_file()` for file parsing. ```python library = bibtexparser.parse_string(bibtex_str) # or bibtexparser.parse_file("my_file.bib") ``` -------------------------------- ### Parse BibTeX File Without Parse Stack Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/examples/middelware.ipynb Parse a BibTeX file while disabling the default middleware stack. This results in different formatting for certain fields, such as authors and titles being enclosed in curly braces. ```python library_no_pstack = bibtexparser.parse_file('bibtex.bib', parse_stack=[]) print(library_no_pstack.entries[0]) ``` -------------------------------- ### Access Specific Entry Field Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/examples/middelware.ipynb Access a specific field, such as the 'author' field, from an entry within the parsed BibTeX library. ```python library.entries[0]['author'] ``` -------------------------------- ### Access Comment Attributes Source: https://github.com/sciunto-org/python-bibtexparser/blob/main/docs/source/quickstart.md Retrieves the raw comment string from a parsed comment block. ```python # Comments have just one specific attribute first_comment = library.comments[0] first_comment.comment # The comment string ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.