我正在尋找一種方法來創建一個動態替換句子中所有單詞的首字母或開頭字母的函式。我創建了一個替換首字母沒問題的函式。
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'
任何幫助將不勝感激。
uj5u.com熱心網友回復:
通過“簡單”分組,您可以訪問具有屬性的匹配項。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
uj5u.com熱心網友回復:
如果出于某種原因需要re ,請忽略它。這是純 Python,不需要任何匯入。
轉換映射是 2 元組的串列。每個元組都有一個from和to值。from和to值不限于長度為 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/485671.html
