簡體   English   中英

通過使用正則表達式加上字典或python中的哈希映射來動態替換句子中單詞的所有開頭和結尾字母

[英]Dynamically replace all starting and ending letters of words in a sentence by using regex plus a dictionary or Hash map in 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

如果出於某種原因需要re ,請忽略它。 這是純 Python,不需要任何導入。

轉換映射是 2 元組的列表。 每個元組都有一個fromto值。 fromto值不限於長度為 1 的字符串。

這個單一的函數處理單詞的開頭和結尾,盡管映射是針對單詞的兩個“結尾”的,因此可能需要一些調整。

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')]))

輸出:

Thiy way yomething that bad to bappen xgain

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM