2016-06-28 7 views
1

나는 $ i [ "CA :"+ $ i + ':'+ ""]의 루프 요소를 각각 대체하는 string Template을 사용하여 example.py 템플릿을 만들려고했습니다. 부분적으로는 작동하지만 마지막 요소 만 대체합니다.문자열 템플릿을 사용하는 동안 모든 루프 요소를 한 줄에 추가하는 방법은 무엇입니까?

그러나 모든 값을 특정 형식으로 한 줄에 추가하고 싶습니다. 예를 들어

:

일을 내 현재 스크립트는 것은 다음과

for i in range(1,4): 
    #It takes each "i" elements and substituting only the last element 
    str='''s=selection(self.atoms["CA:"+$i+':'+" "].select_sphere(10)) 

내가 얻고 것은 다음과 같다 :

s=selection(self.atoms["CA:"+3+':'+" "].select_sphere(10)) 

무엇, 나는 기대하고있다.

s=selection (self.atoms["CA:"+1+':'+" "].select_sphere(10),self.atoms["CA:"+2+':'+" "].select_sphere(10),self.atoms["CA:"+3+':'+" "].select_sphere(10)) 

내 스크립트 :

import os from string import Template for i in range(1,4): str=''' s=selection(self.atoms["CA:"+$i+':'+" "].select_sphere(10)) ''' str=Template(str) file = open(os.getcwd() + '/' + 'example.py', 'w') file.write(str.substitute(i=i)) file.close() 

은 내가 원하는 출력을 얻기 위해이 두 개의 스크립트를 사용이 :

import os 
from string import Template 
a=[] 
for i in range(1,4): 
    a.append(''.join("self.atoms["+ "'CA:' "+str(i)+""':'+" "+"]"+".select_sphere(10)")) 

str='''s=selection($a).by_residue()''' 
str=Template(str) 
file = open(os.getcwd() + '/' + 'example.py', 'w') 
file.write(str.substitute(a=a)) 

with open('example.py', 'w') as outfile: 
    selection_template = '''self.atoms["CA:"+{}+':'+" "].select_sphere(10)''' 
    selections = [selection_template.format(i) for i in range(1, 4)] 
    outfile.write('s = selection({})\n'.format(', '.join(selections))) 

답변

2

한 문제가 코드이다 다음과 같이 g이다 모드 'w'을 사용하여 출력 파일을 열 때 for 루프의 각 반복에서 파일을 덮어 씁니다. 그래서 파일의 마지막 파일 만 볼 수 있습니다.

또한 이러한 대체를 수행하려면 string.Template을 사용하지 않을 것입니다. 그냥 str.format()을 사용하십시오. 선택 목록을 생성하고, 최종 문자열을 생성 str.join()을 사용 여기 selection_template

with open('example.py', 'w') as outfile: 
    selection_template = 'self.atoms["CA:"+{}+":"+" "].select_sphere(10)' 
    selections = [selection_template.format(i) for i in range(1, 4)] 
    outfile.write('s = selection({})\n'.format(', '.join(selections))) 

가변 교체하는 자리로 {}을 사용 지능형리스트는 선택 캐릭터를 생성하는 데 사용된다. 그런 다음이 선택 문자열은 ', ' 문자열을 구분 기호로 사용하고 에 대한 호출에 결과 문자열을 삽입하고 다시 str.format()을 사용합니다.

+0

감사합니다. mhawke – DarwinCode

1

이 예제에서는 비교적 이해하기 쉬운 Python의 내장 format 문자열 방법을 사용합니다. 문자열 템플릿을 선호한다면 쉽게 적용 할 수 있습니다.

트릭을 수행하는 두 개의 별도의 작업이 있다는 것을 관찰하는 것입니다

  1. 인수 목록을 만들기는
  2. 대체

가 나는를 사용하여 필요한 출력 라인의 인수 목록 generator-expression 인수를 join으로 변경하여 필요한 반복과 파트 1을 얻은 다음 2 단계를 수행하기위한 간단한 문자열 형식화를 수행하십시오.

문자열의 format 메서드를 메서드 바운드 함수로 사용하여 메서드 호출을 약어로 단순화합니다.

main_format = ''' 
s = selection({}) 
'''.format 
item_format = 'self.atoms["CA:"+{s}+\':\'+" "].select_sphere(10)'.format 
items = ", ".join(item_format(s=i) for i in range(1, 4)) 
print(main_format(items))