Debian Codegraph @

examples/bibtex.py

raw
1 #!/usr/bin/env python
2
3 # The references are parsed from a BibTeX database, so we import the
4 # corresponding parser.
5 from citeproc.source.bibtex import BibTeX
6
7 # Import the citeproc-py classes we'll use below.
8 from citeproc import CitationStylesStyle, CitationStylesBibliography
9 from citeproc import formatter
10 from citeproc import Citation, CitationItem
11
12
13 # Parse the BibTeX database.
14
15 bib_source = BibTeX('xampl.bib')
16
17
18 # load a CSL style (from the current directory)
19
20 bib_style = CitationStylesStyle('harvard-cite-them-right', validate=False)
21
22
23 # Create the citeproc-py bibliography, passing it the:
24 # * CitationStylesStyle,
25 # * BibliographySource (BibTeX in this case), and
26 # * a formatter (plain, html, or you can write a custom formatter)
27
28 bibliography = CitationStylesBibliography(bib_style, bib_source,
29 formatter.plain)
30
31
32 # Processing citations in a document needs to be done in two passes as for some
33 # CSL styles, a citation can depend on the order of citations in the
34 # bibliography and thus on citations following the current one.
35 # For this reason, we first need to register all citations with the
36 # CitationStylesBibliography.
37
38 citation1 = Citation([CitationItem('whole-collection')])
39 citation2 = Citation([CitationItem('whole-set'), CitationItem('misc-full')])
40 citation3 = Citation([CitationItem('techreport-full')])
41 citation4 = Citation([CitationItem('mastersthesis-minimal')])
42 citation5 = Citation([CitationItem('inproceedings-full'),
43 CitationItem('unpublished-full')])
44
45 bibliography.register(citation1)
46 bibliography.register(citation2)
47 bibliography.register(citation3)
48 bibliography.register(citation4)
49 bibliography.register(citation5)
50
51
52 # In the second pass, CitationStylesBibliography can generate citations.
53 # CitationStylesBibliography.cite() requires a callback function to be passed
54 # along to be called in case a CitationItem's key is not present in the
55 # bibliography.
56
57 def warn(citation_item):
58 print("WARNING: Reference with key '{}' not found in the bibliography."
59 .format(citation_item.key))
60
61
62 print('Citations')
63 print('---------')
64
65 print(bibliography.cite(citation1, warn))
66 print(bibliography.cite(citation2, warn))
67 print(bibliography.cite(citation3, warn))
68 print(bibliography.cite(citation4, warn))
69 print(bibliography.cite(citation5, warn))
70
71
72 # And finally, the bibliography can be rendered.
73
74 print('')
75 print('Bibliography')
76 print('------------')
77
78 for item in bibliography.bibliography():
79 print(str(item))