Python:LaTeX pdf生成的字符串中插入变量

2024-09-27 09:27:39 发布

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

你好,我对Python相当陌生,我想自动生成一些latex pdf报告。所以我想创建一个函数,它以x个字符串变量作为输入,并将它们插入到一个预定义的latex文本中,这样它就可以被编译为报表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的输出为: “在atsumi有300台ge风力涡轮机,这些都在日本”


Tags: reportcmdpdfossiteproccountrylatex
2条回答

从这里开始:

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)

应该是:

^{pr2}$

尝试使用str.format()

report = "On {} there are 300 {} wind turbines, these lies in {}".format(site, turbine, country)

如果您愿意,您可以使用%,但是请注意,这是旧样式:

^{pr2}$

注意:我不认为在您的案例中需要使用原始字符串。在

相关问题 更多 >

    热门问题