简体   繁体   中英

Python3 text replacement optimization

My question is about optimizing how I'm currently doing text replacement.

I have a script I'm building that presents questions with variables inside that get replaced with random actual values when the script is run.

My script currently performs this similar to the following (using the random library):

def rand_var():
    rndvar = ['one', 'two', 'three']
    shuffle(rndvar)
    return rndvar

rndvar = rand_var()

x = 'blah blah VAR1 blah blah VAR2 blah blah'

x = x.replace('VAR1', rndvar[0])
x = x.replace('VAR2', rndvar[1])

The rndvar list is randomized, and within string x VAR1 is replaced with the first randomized element, VAR2 is replaced with the second.

I am wondering if there is a way to rewrite the multiple x = x.replace lines so that I can still specify the variables within the string (the question) as VAR1 VAR2 etc, but have the single replacement line know that VAR1 means replace with rndvar[0] and VAR2 means replace with rndvar[1] etc.

My questions (strings) will contain elements from multiple lists representing different things (but all strings).

Thank you for all the responses, I appreciate it!

One option for single-pass replacement is re.sub :

x = re.sub(r'\bVAR(\d+)\b', lambda m: rndvar[int(m.group(1)) - 1], x)

You could also use a simple zip loop to replace in passes:

for placeholder, replacement in enumerate(('VAR1', 'VAR2'), rndvar):
    x = x.replace(placeholder, replacement)

You can use regular expressions and string formatting:

import re
from random import shuffle
def rand_var():
   rndvar = ['one', 'two', 'three']
   shuffle(rndvar)
   return rndvar

rndvar = rand_var()

x = 'blah blah VAR1 blah blah VAR2 blah blah'
new_x = re.sub('(?<=\s)VAR\d+(?=\s)', '{}', x).format(*[rndvar[i] for i in map(int, re.findall('(?<=VAR)\d+', x))])

Output (randomly generated):

'blah blah one blah blah two blah blah'

You can easily loop through the rndVar array and use the index to specify the replace string

def rand_var():
    rndvar = ['one', 'two', 'three']
    shuffle(rndvar)
    return rndvar

rndvar = rand_var() #['one', 'two', 'three']

x = 'blah blah VAR1 blah blah VAR2 blah blah'

#For every rndvar item, replace VAR+it's pos with the current rndVar value
for i in range(len(rndvar)):
   x = x.replace("VAR"+str(i+1),rndvar[i])

You can try this

for i in range(1,3):
    x.replace ("VAR{}".format(i), rndvar[i])

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