如何编写包含多个循环元素的String模板文件?

How to write String template file with multiple loop elements?

我在字符串模板中编写循环元素时遇到如下小问题:当我尝试从三个循环元素制作字符串模板时,我只能打印最后一个元素而不是前两个元素。我相信该错误是由于写入文件时出现的一些问题,但我无法了解我的代码的实际问题是什么。所以如果有人能帮我解决这个问题。

My SCRIPT:

from string import Template
import os

AMONIOACIDS = {'A': 'ALA', 'C': 'CYS', 'E': 'GLU', 'D': 'ASP', 'G': 'GLY',
           'F': 'PHE', 'I': 'ILE', 'H': 'HIS', 'K': 'LYS', 'M': 'MET',
           'L': 'LEU', 'N': 'ASN', 'Q': 'GLN', 'P': 'PRO', 'S': 'SER',
           'R': 'ARG', 'T': 'THR', 'W': 'TRP', 'V': 'VAL', 'Y': 'TYR'}

rPrS={'C': '102', 'A': '104','H': '12'}


a=[]
b=[]
count=1
for single, third in AMONIOACIDS.iteritems():
   for rS,rP in rPrS.iteritems():
       if rS == single:
            a.append(["s"+str(count)+"=selection(mdl1.chains["+chain+"].residues["+rP+"])"])
            b.append(["s"+str(count)+".mutate(residue_type='"+third+"')"])


str='''Loop elements\n'''
for i,j in zip (a,b):
    i=''.join(i)
    j=''.join(j)
    str+='''$i\n'''
    str+='''$j\n'''
str=Template(str)
str.substitute(i=i, j=j)
file = open(os.getcwd() + '/' + 'model.py', 'w')
file.write(str.substitute(i=i,j=j))
file.close()

预期输出:

Loop elements
s1=selection(mdl1.chains[A].residues[104])
s1.mutate(residue_type='ALA')
s2=selection(mdl1.chains[A].residues[102])
s2.mutate(residue_type='CYS')
s3=selection(mdl1.chains[A].residues[12])
s3.mutate(residue_type='HIS')

我得到了什么:

Loop elements
s3=selection(mdl1.chains[A].residues[12])
s3.mutate(residue_type='HIS')
s3=selection(mdl1.chains[A].residues[12])
s3.mutate(residue_type='HIS')
s3=selection(mdl1.chains[A].residues[12])
s3.mutate(residue_type='HIS')

您的模板正在从 for 循环的 ij 的最后一个值中获取其替换值。您需要保留上一次迭代的值。如何?您可以使用字典和计数来存储和区分每次迭代的值。

你可以substitute values in a template using a dictionary。我在每次迭代中使用 count 变量创建相应的字典键:i_0i_1i_2j_0j_1j_2.这些相同的名称在模板 $i_0$i_1$i_2$j_0$j_1$j_2 中用作标识符。

safe_substitute 将每个键的值安全地替换到模板中,例如将键 i_0 替换为模板标识符 $i_0


字典在每次迭代时存储 ij 的所有值,模板中的替换是在字典中的每个键处采用适当的值完成的。这部分应该修复它:

# your previous lines of code

count = 0
d = {}
s='''Loop elements\n'''
for i,j in zip (a,b):
    d['i_{}'.format(count)] = ''.join(i)
    d['j_{}'.format(count)] = ''.join(j)
    s+='$i_{}\n'.format(count)
    s+='$j_{}\n'.format(count)
    count += 1

print(str)
print(d)
s=Template(s)
file = open(os.getcwd() + '/' + 'model.py', 'w')
file.write(s.safe_substitute(d))
file.close()

我已将名称 str 替换为 s 以避免隐藏内置 str。修复前的代码块中不需要进行其他更改。