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

3
我是一名Python新手,所以我不确定这个操作的确切名称,因此我在搜索相关信息时遇到了困难。
基本上,我想要一个字符串,例如:
"[[size]] widget that [[verb]] [[noun]]"

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

我想把这个字符串解释成一种元语言,这样我就可以从这些列表的排列组合中生成很多句子。作为一种元语言,我还可以使用那些预定义的列表来生成更多的排列组合。

Python是否有像这样的变量替换功能?如果我想搜索相关信息,应该用什么术语描述这个操作呢?


学习 Python 两个月后,我又遇到了这个问题,感到有些尴尬。现在看来,这是 Python 的一个基本方面,但当我开始学习时,我对 Python 中的字符串类一无所知... - Mike Lewis
5个回答

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)

"{{size}}个小部件{{verb}}{{noun}}".format().format(size=23, verb="测试", noun="人") - Vikram Ray

2

如果您有 sizesverbsnouns 列表,以下是一种可能的实现方式:

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)

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

1
你想要使用 re.sub() 或其相应的正则表达式对象方法,并配合一个回调函数。

0

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接