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

时间:2018-06-18 08:47:54

标签: python subprocess pdf-generation pdflatex latex-environment

您好我是Python的新手,我想自动生成一些乳胶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的输出读取: "在atsumi有300个GE风力涡轮机,这些风力涡轮机位于日本"

2 个答案:

答案 0 :(得分:1)

这是一个开始:

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)

答案 1 :(得分:1)

尝试使用str.format()

%

如果您愿意,可以使用report = "On %s there are 300 %s wind turbines, these lies in %s" % (site, turbine, country) 代替,请注意,这是旧样式:

*ngIf="tileinfo.progress !== 0"

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