假设字符串myStr包含三个特殊字符。
myStr = "emdash —; delta Δ; thin space: ;"进一步假设我们希望通过LaTeX将此字符串写入幽门文档。
如果将字符串写入LaTeX文档,则在其编译过程中会发生错误:
import pylatex
doc = pylatex.Document()
with doc.create(pylatex.Section('myStr -- not encoded')):
doc.append(myStr)
doc.generate_pdf("myStr_notEncoded", clean_tex=False)
...
! Package inputenc Error: Unicode character Δ (U+0394)
(inputenc) not set up for use with LaTeX.
...
! Package inputenc Error: Unicode character (U+2009)
(inputenc) not set up for use with LaTeX.
...如果我们首先通过幽门栓对字符串进行编码,则特殊字符要么用各自的LaTeX编码(emdash;delta)表示,要么以我不清楚的方式进行编码(瘦空间)。
import pylatexenc
from pylatexenc import latexencode
myStr_latex = pylatexenc.latexencode.unicode_to_latex(myStr)
doc = pylatex.Document()
with doc.create(pylatex.Section('myStr')):
doc.append(myStr_latex)
doc.generate_pdf("myStr", clean_tex=False)

如何将字符串写入LaTeX文档,以便在用pdflatex编译时将特殊字符打印为实际字符?
编辑1:
我还试图为未编码的路径更改LaTeX文档中的默认编码,但这也会导致一系列编译错误。
doc.preamble.append(pylatex.NoEscape("\\usepackage[utf8]{inputenc}"))发布于 2022-07-27 06:07:17
你和你的pylatexenc解决方案关系密切。当你自己编码胶乳时,例如用pylatexenc.latexencode.unicode_to_latex(),你必须确保你告诉幽门,字符串不应该是额外的转义。风趣
使用常规的LaTeX字符串可能并不像看起来那么简单,因为默认情况下几乎所有字符串都是转义的.在有些情况下,原始LaTeX字符串应该直接在文档中使用。这就是为什么
NoEscape字符串类型存在的原因。这只是str的一个子类,但不会转义
换句话说,只需确保使用NoEscape来告诉pylatex您的字符串已被编码为latex,并且不再对其进行编码:
import pylatex
from pylatexenc import latexencode
myStr_latex = latexencode.unicode_to_latex(myStr)
doc = pylatex.Document()
with doc.create(pylatex.Section('myStr')):
doc.append(pylatex.utils.NoEscape(myStr_latex))
doc.generate_pdf("myStr", clean_tex=False)

发布于 2022-07-18 13:43:45
在找到更好的解决方案之前,一个可行的(虽然不是更可取的)解决方案是通过包newunicodechar对所有违规字符进行编码。
doc.preamble.append(pylatex.Command('usepackage', 'newunicodechar'))
doc.preamble.append(pylatex.NoEscape(r'\newunicodechar{²}{\ensuremath{{}^2}}'))
doc.preamble.append(pylatex.NoEscape(r'\newunicodechar{ }{\,}'))
doc.preamble.append(pylatex.NoEscape(r"\newunicodechar{′}{'}"))
doc.preamble.append(pylatex.NoEscape(r'\newunicodechar{−}{\ensuremath{-}}'))
doc.preamble.append(pylatex.NoEscape(r'\newunicodechar{∶}{\ensuremath{:}}'))
doc.preamble.append(pylatex.NoEscape(r'\newunicodechar{≤}{\ensuremath{\leq}}'))
doc.preamble.append(pylatex.NoEscape(r'\newunicodechar{≥}{\ensuremath{\geq}}'))
doc.preamble.append(pylatex.NoEscape(r'\newunicodechar{α}{\ensuremath{\alpha}}'))
doc.preamble.append(pylatex.NoEscape(r'\newunicodechar{β}{\ensuremath{\beta}}'))
doc.preamble.append(pylatex.NoEscape(r'\newunicodechar{Δ}{\ensuremath{\Delta}}')) ## (U+0394)
doc.preamble.append(pylatex.NoEscape(r'\newunicodechar{∆}{\ensuremath{\Delta}}')) ## (U+2206)
doc.preamble.append(pylatex.NoEscape(r'\newunicodechar{λ}{\ensuremath{\lambda}}'))
doc.preamble.append(pylatex.NoEscape(r'\newunicodechar{μ}{\ensuremath{\mu}}'))https://stackoverflow.com/questions/73021806
复制相似问题