我创建了一个函数,根据字符位置用多个模式替换单个字符的多个实例。
我发现有两种方法可以做到这一点:
def xSubstitution(target_string):
while target_string.casefold().find('x') != -1:
x_finded = target_string.casefold().find('x')
if (x_finded == 0 and target_string[1] == ' ') or (target_string[x_finded-1] == ' ' and
((target_string[-1] == 'x' or 'X') or target_string[x_finded+1] == ' ')):
target_string = target_string.replace(target_string[x_finded], 'ecks', 1)
elif (target_string[x_finded+1] != ' '):
target_string = target_string.replace(target_string[x_finded], 'z', 1)
else:
target_string = target_string.replace(target_string[x_finded], 'cks', 1)
return(target_string)进口re
multipleRegexSubstitutions(句子):
patterns = {(r'^[xX]\s'): 'ecks ', (r'[^\w]\s?[xX](?!\w)'): 'ecks',
(r'[\w][xX]'): 'cks', (r'[\w][xX][\w]'): 'cks',
(r'^[xX][\w]'): 'z',(r'\s[xX][\w]'): 'z'}
regexes = [
re.compile(p)
for p in patterns
]
for regex in regexes:
for match in re.finditer(regex, sentence):
match_location = sentence.casefold().find('x', match.start(), match.end())
sentence = sentence.replace(sentence[match_location], patterns.get(regex.pattern), 1)
return sentence据我所知,第二个函数中唯一的问题是正则表达式模式。有人能帮我吗?
编辑:对不起,我忘了告诉您,regexes在字符串中寻找不同的x字符,并将x替换为“Z”的单词,中间或结尾的单词“cks”,如果是“x”字符,则替换为“ecks”。
发布于 2021-04-15 21:55:13
您需要\b (word边界)和\B ( word边界以外的位置):
在“Z”一词的乞讨中替换X
re.sub(r'\bX\B', 'Z', s, flags=re.I)位于单词“cks”的中间或结尾
re.sub(r'\BX', 'cks', s, flags=re.I)如果它是单独的'x‘字符,则用’
‘替换为'ecks’
re.sub(r'\bX\b', 'ecks', s, flags=re.I)发布于 2021-04-15 18:20:09
我只需使用以下一组替换:
string = re.sub(r"\b[Xx]\b", "ecks", string)
string = re.sub(r"\b[Xx](?!\s)", "Z", string)
string = re.sub(r"(?<=\w)[Xx](?=\w)", "cks", string)这里,
(?!\s) 只是断言regex不匹配任何空格字符,
\b编辑:最后一个正则表达式也将匹配单词开头的x或X。所以我们可以使用以下方法,
(?<=\w)[xX](?=\w)以确保在x或X之前/之后必须有一个字符X。
https://stackoverflow.com/questions/67113324
复制相似问题