Home > Back-end >  Dynamically replace all starting and ending letters of words in a sentence by using regex plus a dic
Dynamically replace all starting and ending letters of words in a sentence by using regex plus a dic

Time:06-05

I'm looking for a way to create a function that dynamically replaces all the initial or beginning letters of words in a sentence. I created a function that replaces the initial letters no problem.

def replace_all_initial_letters(original, new, sentence):
    new_string = re.sub(r'\b' original, new, sentence)
    return new_string

test_sentence = 'This was something that had to happen again'

print(replace_all_initial_letters('h', 'b', test_sentence))

Output: 'This was something that bad to bappen again'

I would however like to be able to enter multiple options into this function using a dictionary or Hash Map. For example like using the following:

initialLetterConversion = {
    'r': 'v',
    'h': 'b'
}

Or I think there might be a way to do this using regex grouping perhaps.

I'm also having trouble implementing this for ending letters. I tried the following function but it does not work

def replace_all_final_letters(original, new, sentence):
    new_string = re.sub(original r'/s', new, sentence)
    return new_string

print(replace_all_final_letters('n', 'm', test_sentence))

Expected Output: 'This was something that had to happem agaim'

Any help would be greatly appreciated.

CodePudding user response:

By "simple" grouping you can access to the match with the lastindex attribute. Notice that such indexes starts from 1. re.sub accept as second argument a callback to add more flexibility for custom substitutions. Here an example of usage:

import re


mapper = [
    {'regex': r'\b(w)', 'replace_with': 'W'},
    {'regex': r'\b(h)', 'replace_with': 'H'}]


regex = '|'.join(d['regex'] for d in mapper)


def replacer(match):
    return mapper[match.lastindex - 1]['replace_with'] # mapper is globally defined

text = 'This was something that had to happen again'

out = re.sub(regex, replacer, text)
print(out)
#This Was something that Had to Happen again

CodePudding user response:

Ignore this if, for some reason, re is required for this. This is plain Python with no need for any imports.

The conversion map is a list of 2-tuples. Each tuple has a from and to value. The from and to values are not limited to a string of length 1.

This single function handles both the beginning and end of words although the mapping is for both 'ends' of the word and may therefore need some adaptation.

sentence = 'This was something that had to happen again'

def func(sentence, conv_map):
    words = sentence.split()
    for i, word in enumerate(words):
        for f, t in conv_map:
            if word.startswith(f):
                words[i] = t   word[len(f):]
                word = words[i]
            if word.endswith(f):
                words[i] = word[:-len(f)]   t
    return ' '.join(words)

print(func(sentence, [('h', 'b'), ('a', 'x'), ('s', 'y')]))

Output:

Thiy way yomething that bad to bappen xgain
  • Related