[英]Python find all matching substring patterns and replace substring
我想搜索一個句子是否具有特定模式。 如果找不到,則不執行任何操作。 如果找到模式,則用字符串中的另一個子字符串替換模式。
line1 = "Who acted as `` Bruce Wayne '' in the movie `` Batman Forever '' ?"
#Desired Result: Who acted as ``Bruce_Wayne'' in the movie ``Batman_Forever'' ?
#This is what I have tried..
def findSubString(raw_string, start_marker, end_marker):
start = raw_string.index(start_marker) + len(start_marker)
end = raw_string.index(end_marker, start)
return raw_string[start:end]
phrase = findSubString(line1, "``", "''")
newPhrase = phrase.strip(' ').replace(' ', '_')
line1 = line1.replace(phrase, newPhrase)
當前結果: Who acted as ``Bruce_Wayne'' in the movie `` Batman Forever '' ?
到目前為止,我設法找到了句子中的第一個匹配項,但沒有找到第二個。 如何搜索具有匹配模式的所有事件?
使用正則表達式:
import re
def findSubString(raw_string, start_marker, end_marker):
return re.sub(
r'(?<={}).*?(?={})'.format(re.escape(start_marker), re.escape(end_marker)),
lambda m: m.group().strip().replace(' ', '_'),
raw_string)
line1 = "Who acted as `` Bruce Wayne '' in the movie `` Batman Forever '' ?"
line1 = findSubString(line1, "``", "''")
assert line1 == "Who acted as ``Bruce_Wayne'' in the movie ``Batman_Forever'' ?"
沒有正則表達式:
def findSubString(raw_string, start_marker, end_marker):
result = []
rest = raw_string
while True:
head, sep, tail = rest.partition(start_marker)
if not sep:
break
body, sep, tail = tail.partition(end_marker)
if not sep:
break
result.append(head + start_marker + body.strip().replace(' ', '_') + end_marker)
rest = tail
result.append(rest)
return ''.join(result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.