简体   繁体   中英

iterating replacing string in a text

I'm writing a program that has to replace the string “+” by “!”, and strings “*+” by “!!” in a particular text. As an example, I need to go from:

 some_text  = ‘here is +some*+ text and also +some more*+ text here’

to

 some_text_new = ‘here is !some!! text and also !some more!! text here’

You'll notice that “+” and “*+” enclose particular words in my text. After I run the program, those words need be enclosed between “!” and “!!” instead.

I wrote the following code but it iterates several times before giving the right output. How can I avoid that iteration?….

    def many_cues(value):
        if has_cue_marks(value) is True:
            add_text(value)
            #print value


    def has_cue_marks(value):
        return '+' in value and'+*' in value

    def add_text(value):
        n = '+'
        m = "+*"
        text0 = value
        for n in text0:
            text1 = text0.replace(n, ‘!', 3)
            print text1
        for m in text0:
            text2 = text0.replace(m, ‘!!’, 3)
            print text2
>>> x = 'here is +some*+ text and also +some more*+ text here'
>>> x = x.replace('*+','!!')
>>> x
'here is +some!! text and also +some more!! text here'
>>> x = x.replace('+','!')
>>> x
'here is !some!! text and also !some more!! text here'

The final argument to replace is optional - if you leave it out, it will replace all instances of the word. So, just use replace on the larger substring first so you don't accidentally take out some of the smaller, then use replace on the smaller, and you should be all set.

It can be done using regex groups

import re

def replacer(matchObj):
    if matchObj.group(1) == '*+':
        return '!!'
    elif matchObj.group(2) == '+'
        return '!'

text = 'here is +some*+ text and also +some more*+ text here'
replaced = re.sub(r'(\*\+)|(\+)', replacer, text)

Notice that the order of the groups are important since you have common characters in the two patterns you want to replace

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