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

3 投票
5 回答
6506 浏览
提问于 2025-04-15 22:54

我刚开始学Python,所以不太确定这个操作叫什么名字,因此在网上查资料时遇到了困难。

简单来说,我想要一个像这样的字符串:

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

其中,size、verb和noun都是列表。

我想把这个字符串当作一种元语言,这样我就可以通过这些列表的不同组合来生成很多句子。作为一种元语言,我还可以创建其他字符串,利用这些预定义的列表来生成更多的组合。

在Python中有没有类似于这种变量替换的功能?如果我想在网上搜索,应该用什么词来描述这个操作呢?

5 个回答

2

试试这个脚本:

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
7

如果你把你的语法改成这样:

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

那么你可以使用字符串的 format 方法来进行替换:

"{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)
2

如果你有 sizesverbesnounes 这些列表,下面是一个可能的实现方法:

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)

撰写回答