pybtex是否支持.bib文件中的重音/特殊字符?

2024-04-25 01:09:49 发布

您现在位置:Python中文网/ 问答频道 /正文

from pybtex.database.input import bibtex
parser = bibtex.Parser()
bibdata = parser.parse_file("sample.bib")

上面的代码片段在解析.bib文件时工作得非常好,但是它似乎不支持重音字符,比如{\"u}或{}(来自LaTeX)。只是想确认一下pybtex是否支持它。在

例如,根据LaTeX/Special CharactersHow to write “ä” and other umlauts and accented letters in bibliography?\"{o}应该转换为ö,而{}也是如此。在


Tags: andsamplefromimportparserinputparsebibtex
2条回答

版本现在支持此功能:strong。在

目前还没有。但是在使用pybtex处理bib文件之前,您可以使用latex编解码器读取bib文件,例如使用https://pypi.python.org/pypi/latexcodec/该编解码器将为您将(广泛的)latex命令转换为unicode。在

但是,您必须在后处理阶段删除括号。为什么?为了优雅地处理bibtex代码,\"{U}转换为{Ü},而不是Ü,以防止标题中的小写。以下示例演示了这种行为:

import pybtex.database.input.bibtex
import pybtex.plugin
import codecs
import latexcodec

style = pybtex.plugin.find_plugin('pybtex.style.formatting', 'plain')()
backend = pybtex.plugin.find_plugin('pybtex.backends', 'latex')()
parser = pybtex.database.input.bibtex.Parser()
with codecs.open("test.bib", encoding="latex") as stream:
    # this shows what the latexcodec does to the source
    print stream.read()
with codecs.open("test.bib", encoding="latex") as stream:
    data = parser.parse_stream(stream)
for entry in style.format_entries(data.entries.itervalues()):
    print entry.text.render(backend)

在哪里测试.bib是

^{pr2}$

这将打印latexcodec如何转换测试.bib转换为unicode(为可读性而编辑):

@Article{test,
   author = {John Doe}, title = {Testing ÜTEST {Ü}TEST},
   journal = {Journal of Test}, year = {2000},
}

后面是pybtex呈现的条目(在本例中,生成latex代码):

John Doe.
\newblock Testing ütest {Ü}test.
\newblock \emph{Journal of Test}, 2000.

如果编解码器去掉括号,pybtex就会错误地转换大小写。{cd4}更明显的是,不能移除cd4}。在

一个明显的缺点是,如果渲染到非LaTeX后端,则必须在后处理阶段移除括号。但是无论如何,您可能希望这样做来处理任何特殊的LaTeX命令(例如\url)。如果pybtex能为你做到这一点那就太好了,但目前还没有。在

pylatexenc(https://pypi.org/project/pylatexenc/

from pylatexenc.latex2text import LatexNodes2Text 

latex_text = 'Gl{\\"o}ckner'
text = LatexNodes2Text().latex_to_text(latex_text)

print(text) # Glöckner


相关问题 更多 >