试试这个脚本:
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个月到Python,我回来了这个问题,感到羞怯。看起来像Python现在这样一个基本的方面,但我开始时并不知道Python中的字符串类的第一件事... – 2010-07-08 21:24:39