2010-05-19 4 views
3

저는 파이썬을 처음 접했으므로이 연산이 무엇인지 정확히 알지 못합니다. 따라서 정보를 검색하는 데 어려움을 겪고 있습니다.Python에서 템플릿 문자열을 구문 분석하려면 어떻게해야합니까?

기본적으로 나는 문자열을 가지고 싶습니다 같은 : 크기, 동사와 명사는 각 목록이 있습니다

"[[size]] widget that [[verb]] [[noun]]" 

.

문자열을 메타 언어로 해석하여 목록에서 순열을 많이 만들 수 있습니다. 메타 언어로, 나는 또한 더 많은 순열을 생성하기 위해 그 미리 정의 된리스트를 사용하는 다른 문자열을 만들 수있을 것이다.

파이썬에서 이와 같이 변수를 대체 할 수있는 기능이 있습니까? Google에이 작업을 설명하면이 작업을 설명하는 용어는 무엇입니까?

+0

파이썬으로 2 개월이 질문에 다시 돌아 왔고 양떼를 느꼈습니다. 지금 파이썬의 기본적인 측면처럼 보입니다.하지만 파이썬에서 내가 시작했을 때 문자열 클래스에 관한 첫 번째 것을 알지 못했습니다 ... –

답변

2

여기에 하나의 가능한 구현하면 경우 : 당신이 그런 다음 대체 할 문자열의 format 방법을 사용할 수 있습니다

"{size} widget that {verb} {noun}" 

에 구문을 변경하는 경우

1

re.sub() 또는 그 regex 객체와 동일한 메소드를 콜백 함수와 함께 사용하려고합니다.

"{size} widget that {verb} {noun}".format(size='Tiny',verb='pounds',noun='nails') 

또는

choice={'size':'Big', 
    'verb':'plugs', 
    'noun':'holes'} 
"{size} widget that {verb} {noun}".format(**choice) 
4

sizes, verbes, nounes 개 목록 :

import itertools, string 

t = string.Template("$size widget that $verb $noun") 
for size, verb, noun in itertools.product(sizes, verbes, nounes): 
    print t.safe_substitute(size=size, verb=verb, noun=noun) 
1

이 스크립트를 시도해보십시오

import random #just needed for the example, not the technique itself 
import re # regular expression module for Python 

template = '[[size]] widget that [[verb]] [[noun]]' 
p = re.compile('(\[\[([a-z]+)\]\])') # match placeholder and the word inside 
matches = p.findall(template) # find all matches in template as a list 

#example values to show you can do substitution 
values = { 
    'size': ('tiny', 'small', 'large'), 
    'verb': ('jumps', 'throws', 'raises'), 
    'noun': ('shark', 'ball', 'roof') 
} 

print 'After each sentence is printed, hit Enter to continue or Ctrl-C to stop.' 

while True: # forever 
    s = template 
    #this loop replaces each placeholder [[word]] with random value based on word 
    for placeholder, key in matches: 
     s = s.replace(placeholder, random.choice(values[key])) 
    print s 
    try: 
     raw_input('') # pause for input 
    except KeyboardInterrupt: #Ctrl-C 
     break # out of loop 

예 출력 :

large widget that jumps ball 

small widget that raises ball 

small widget that raises ball 

large widget that jumps ball 

small widget that raises ball 

tiny widget that raises shark 

small widget that jumps ball 

tiny widget that raises shark 
0

정규식은 과잉이다. 다음과 같이 크기 동사와 명사 변수를 설정하려면 루프를 사용하십시오.

print("%(size)s widget that %(verb)s %(noun)s" % {"size":size, "verb":verb, "noun":noun}) 
관련 문제