How to parse a template in Python?

I am new to Python, so I'm not sure what this operation is called, so it's hard for me to find the information in it.

Basically, I would like to have a line such as:

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

Where size, verb and noun are a list.

I would like to interpret the string as a metalanguage so that I can make many sentences from permutations from lists. As a metalanguage, I would also be able to make other lines that use these predefined lists to generate more permutations.

Are there any possibilities for substituting variables like this in Python? What term describes this operation if I should just google it?

+3
source share
5 answers

, sizes, verbes, nounes :

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

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

string 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)
+4

You want to use re.sub()either its equivalent object method using the callback function.

+1
source

Try running the 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

Output Example:

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
source

Regex is full. Use loops to set verbs of size and name variables:

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

Source: https://habr.com/ru/post/1746267/


All Articles