0

您好,我对 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 风力涡轮机,这些位于日本”

4

2 回答 2

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)
于 2018-06-18T08:56:33.423 回答
1

尝试使用str。格式()

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)

注意:在您的情况下,我认为不需要使用原始字符串。

于 2018-06-18T08:57:03.713 回答