首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python:在字符串中插入变量以生成LaTeX pdf

问Python:在字符串中插入变量以生成LaTeX pdf
EN

Stack Overflow用户
提问于 2018-06-18 08:47:53
回答 2查看 2.1K关注 0票数 0

你好,我是Python的新手,我想要自动生成一些latex pdf报告。因此,我想要创建一个函数,它以x个字符串变量作为输入,并将它们插入到预定义的latex文本中,这样就可以将其编译为report。我真的希望有人能帮我解决这个问题。我尝试了如下所示的做法,这显然是行不通的:

代码语言:javascript
复制
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风力涡轮机,这些都在日本。”

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-06-18 08:56:33

以下是一个开始:

代码语言:javascript
复制
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)

应:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2018-06-18 08:57:03

尝试使用format()

代码语言:javascript
复制
report = "On {} there are 300 {} wind turbines, these lies in {}".format(site, turbine, country)

如果您喜欢使用%,那么请注意,这是旧的风格:

代码语言:javascript
复制
report = "On %s there are 300 %s wind turbines, these lies in %s" % (site, turbine, country)

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50905707

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档