通过使用正则表达式加上字典或python中的哈希映射来动态替换句子中单词的所有开始和结束字母

标点符号

我正在寻找一种方法来创建一个动态替换句子中所有单词的首字母或开头字母的函数。我创建了一个替换首字母没问题的函数。

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'

但是,我希望能够使用字典或哈希映射在此函数中输入多个选项。例如像使用以下内容:

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

或者我认为可能有一种方法可以使用正则表达式分组来做到这一点。

我在结束字母时也遇到了麻烦。我尝试了以下功能,但它不起作用

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'

任何帮助将不胜感激。

通过“简单”分组,您可以访问具有属性的匹配项。lastindex请注意,此类索引从 1 开始。re.sub接受回调作为第二个参数,以增加自定义替换的灵活性。这里是一个使用示例:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章