简体   繁体   中英

How do I parse a templated string in Python?

I'm new to Python, so I'm not sure exactly what this operation is called, hence I'm having a hard time searching for information in it.

Basically I'd like to have a string such as:

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

Where size, verb, and noun are each a list.

I'd like to interpret the string as a metalanguage, such that I can make lots of sentences out permutations from the lists. As a metalanguage, I'd also be able to make other strings that use those pre-defined lists to generate more permutations.

Are there any capabilities for variable substitution like this in Python? What term describes this operation if I should just Google it?

If you change your syntax to

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

Then you could use string's format method to do the substitutions:

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

or

choice={'size':'Big',
    'verb':'plugs',
    'noun':'holes'}
"{size} widget that {verb} {noun}".format(**choice)

Here's one possible implementation if you have sizes , verbes , nounes lists:

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)

您希望将re.sub()或其正则表达式对象等效方法与回调函数一起使用。

Try this script:

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

Example output:

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

Regex is overkill. Use loops to set the size verb and noun variables then:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM