【问题标题】:Python: Insert variable in string for LaTeX pdf generationPython:在字符串中插入变量以生成 LaTeX pdf
【发布时间】:2018-06-18 08:47:53
【问题描述】:

您好,我对 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 风力涡轮机,这些都在日本"

【问题讨论】:

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


    【解决方案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)
    

    【讨论】:

    • 我可以问你一个与此相关的快速问题吗?我想编译一些包含以下短语的 LaTeX 代码: \documentclass[a4paper]{jpconf} \usepackage{graphicx} \usepackage{titling} 我如何避免使用 .format 方法来排除这些? {jpconf}
    • Python 字符串是不可变的,因此您必须创建一个新字符串。这是一个示例: new_string = old_string.replace("{jpconf}", "")
    【解决方案2】:

    尝试使用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)
    

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

    【讨论】:

      猜你喜欢
      • 2017-03-02
      • 1970-01-01
      • 2015-08-02
      • 1970-01-01
      • 2016-11-11
      • 1970-01-01
      • 1970-01-01
      • 2017-11-11
      相关资源
      最近更新 更多