我想获取一个或多个bibtex条目的文件,并将其输出为html格式的字符串。具体的风格并不那么重要,但我们只说APA。基本上,我想要bibtex2html的功能,但我需要Python API,因为我在Django工作。一些人问了类似的问题here和here。我还发现有人提供了可能的解决方案here。
我遇到的第一个问题是非常基本的,即我甚至无法获得上述解决方案。我一直遇到类似于ModuleNotFoundError: No module named 'pybtex.database'; 'pybtex' is not a package
的错误。我肯定安装了pybtex并且可以在shell中进行基本的API调用没有问题,但每当我尝试导入pybtex.database.whatever或pybtex.plugin时,我都会遇到ModuleNotFound
错误。它可能是python 2 vs python 3的东西吗?我正在使用后者。
第二个问题是我无法理解pybtex python API documentation。具体来说,从我可以告诉它看起来format_from_string
和format_from_file
调用是专门为我想做的设计,但我似乎无法得到正确的语法。具体来说,当我这样做
pybtex.format_from_file('foo.bib',style='html')
我得到pybtex.plugin.PluginNotFound: plugin pybtex.style.formatting.html not found
。我想我只是不理解这个电话应该如何工作,我找不到任何正确的例子。
这是我为类似用例编写的函数 - 将参考书目纳入Pelican生成的网站。
from pybtex.plugin import find_plugin
from pybtex.database import parse_string
APA = find_plugin('pybtex.style.formatting', 'apa')()
HTML = find_plugin('pybtex.backends', 'html')()
def bib2html(bibliography, exclude_fields=None):
exclude_fields = exclude_fields or []
if exclude_fields:
bibliography = parse_string(bibliography.to_string('bibtex'), 'bibtex')
for entry in bibliography.entries.values():
for ef in exclude_fields:
if ef in entry.fields.__dict__['_dict']:
del entry.fields.__dict__['_dict'][ef]
formattedBib = APA.format_bibliography(bibliography)
return "<br>".join(entry.text.render(HTML) for entry in formattedBib)
确保您已安装以下内容:
pybtex==0.22.2
pybtex-apa-style==1.3