Home > Software design >  How to replace a word in a given sentence with a particular pattern if it's case insensitive in
How to replace a word in a given sentence with a particular pattern if it's case insensitive in

Time:04-11

I am given the sentence My team is the BeST team at the tournament. as a test case to create create a function

def case_insensitivity(sentence):
    return new_sentence

which checks a given sentence for a case insensitive word and replaces the case insensitive word with XXX_.

i.e.

print(case_insensitivity('My team is the BeST team at the tournament'))
result
'My team is the XXX_ team at the tournament'

What's the best way to do this? casefold()

CodePudding user response:

Assuming we define the target words as having both a lowercase and uppercase beyond the first character, we can try using re.sub for a regex option:

def case_insensitivity(sentence):
    return re.sub(r'\w (?:[A-Z]\w*[a-z]|[a-z]\w*[A-Z])\w*', 'XXX_', sentence)

print(case_insensitivity('My team is the BeST team at the tournament'))

This prints:

My team is the XXX_ team at the tournament

CodePudding user response:

This is my solution (hopefully I understand well your problem):

  1. you split the sentence intro words.

  2. you loop through all the words

  3. you loop through the letters of the words - starting from the second letter of each word.

  4. check if there are any uppercase letters

  5. if you find uppercase letter you give 1 to the have_to_replace variable.

  6. you make the replacement

    txt = 'My team is the BeST team at the tournament'
    x = txt.split()
    
    for w in x:
        have_to_replace = False
        for l in w[1:]:
            if l != l.casefold():
                have_to_replace = True
        if have_to_replace:
            txt = txt.replace(w, 'XXX_', 1)
    print(txt)
    

For some reason the Code blocking is not working properly for the first 3 lines (and the last). Sorry for that.

  • Related