Python: 在用于 LaTeX pdf 生成的字符串中插入变量
Python: Insert variable in string for LaTeX pdf generation
你好,我是 Python 的新手,我想自动生成一些 latex pdf 报告。所以我想制作一个函数,将 x 个字符串变量作为输入并将它们插入到预定义的乳胶文本中,这样它就可以编译为报告 pdf。我真的希望有人能帮我解决这个问题。我试过如下所示,这显然不起作用:
def insertVar(site, turbine, country):
site = str(site)
turbine = str(turbine)
country = str(country)
report = r'''On %(site)s there are 300 %(turbine)s wind turbines, these lies in %(country)s'''
with open('report.tex','w') as f:
f.write(report)
cmd = ['pdflatex', '-interaction', 'nonstopmode', 'report.tex']
proc = subprocess.Popen(cmd, stdout=PIPE, stderr=PIPE)
proc.communicate()
retcode = proc.returncode
if not retcode == 0:
os.unlink('report.pdf')
raise ValueError('Error {} executing command: {}'.format(retcode, ' '.join(cmd)))
os.unlink('report.tex')
os.unlink('report.log')
insertVar('atsumi', 'ge', 'japan')
所以我希望 PDF 的输出为:
"On atsumi there are 300 ge wind turbines, these lies in japan"
这是一个开始:
report = r'''On %(site)s there are 300 %(turbine)s wind turbines, these lies in %(country)s'''
with open('report.tex','w') as f:
f.write(report)
应该是:
report = r'''On {a}s there are 300 {b}s wind turbines, these lies in {c}s'''.format(a=site, b=turbine, c=country)
with open('report.txt','w') as f:
f.write(report)
尝试使用 str.format():
report = "On {} there are 300 {} wind turbines, these lies in {}".format(site, turbine, country)
如果您愿意,可以使用 %
代替,但请注意,这是旧样式:
report = "On %s there are 300 %s wind turbines, these lies in %s" % (site, turbine, country)
注意:我认为您没有必要使用原始字符串。
你好,我是 Python 的新手,我想自动生成一些 latex pdf 报告。所以我想制作一个函数,将 x 个字符串变量作为输入并将它们插入到预定义的乳胶文本中,这样它就可以编译为报告 pdf。我真的希望有人能帮我解决这个问题。我试过如下所示,这显然不起作用:
def insertVar(site, turbine, country):
site = str(site)
turbine = str(turbine)
country = str(country)
report = r'''On %(site)s there are 300 %(turbine)s wind turbines, these lies in %(country)s'''
with open('report.tex','w') as f:
f.write(report)
cmd = ['pdflatex', '-interaction', 'nonstopmode', 'report.tex']
proc = subprocess.Popen(cmd, stdout=PIPE, stderr=PIPE)
proc.communicate()
retcode = proc.returncode
if not retcode == 0:
os.unlink('report.pdf')
raise ValueError('Error {} executing command: {}'.format(retcode, ' '.join(cmd)))
os.unlink('report.tex')
os.unlink('report.log')
insertVar('atsumi', 'ge', 'japan')
所以我希望 PDF 的输出为: "On atsumi there are 300 ge wind turbines, these lies in japan"
这是一个开始:
report = r'''On %(site)s there are 300 %(turbine)s wind turbines, these lies in %(country)s'''
with open('report.tex','w') as f:
f.write(report)
应该是:
report = r'''On {a}s there are 300 {b}s wind turbines, these lies in {c}s'''.format(a=site, b=turbine, c=country)
with open('report.txt','w') as f:
f.write(report)
尝试使用 str.format():
report = "On {} there are 300 {} wind turbines, these lies in {}".format(site, turbine, country)
如果您愿意,可以使用 %
代替,但请注意,这是旧样式:
report = "On %s there are 300 %s wind turbines, these lies in %s" % (site, turbine, country)
注意:我认为您没有必要使用原始字符串。