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