如何在Python中解析模板化字符串?

如何在Python中解析模板化字符串?,python,Python,我是Python新手,所以我不确定这个操作的确切名称,因此我很难在其中搜索信息 基本上我想要一个字符串,比如: "[[size]] widget that [[verb]] [[noun]]" 其中大小、动词和名词都是一个列表 我想把字符串解释为一种元语言,这样我就可以从列表中排列出许多句子。作为一种元语言,我还能够生成使用这些预定义列表生成更多排列的其他字符串 Python中是否有类似的变量替换功能?如果我只是用谷歌搜索它,哪个术语描述这个操作?你想用它的regex对象等效方法和回调函数一起

我是Python新手,所以我不确定这个操作的确切名称,因此我很难在其中搜索信息

基本上我想要一个字符串,比如:

"[[size]] widget that [[verb]] [[noun]]"
其中大小、动词和名词都是一个列表

我想把字符串解释为一种元语言,这样我就可以从列表中排列出许多句子。作为一种元语言,我还能够生成使用这些预定义列表生成更多排列的其他字符串


Python中是否有类似的变量替换功能?如果我只是用谷歌搜索它,哪个术语描述这个操作?

你想用它的regex对象等效方法和回调函数一起使用。

如果你把语法改为

"{size} widget that {verb} {noun}"
然后您可以使用string的
格式
方法进行替换:

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


如果您有
大小
动词
名词
列表,这里有一个可能的实现:

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)
请尝试以下脚本:

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

正则表达式太过分了。使用循环设置大小动词和名词变量,然后:

print("%(size)s widget that %(verb)s %(noun)s" % {"size":size, "verb":verb, "noun":noun})

进入Python 2个月后,我再次遇到这个问题,感到很不好意思。现在看起来像是Python的一个基本方面,但是当我开始的时候,我对Python中的string类一无所知。。。
print("%(size)s widget that %(verb)s %(noun)s" % {"size":size, "verb":verb, "noun":noun})