Python-如何匹配和替换给定字符串中的单词?
我有一个大集合的数组列表,还有一个输入字符串。如果在输入字符串中找到大集合,它将替换为给定选项 我尝试了以下操作,但返回错误:Python-如何匹配和替换给定字符串中的单词?,python,python-2.7,Python,Python 2.7,我有一个大集合的数组列表,还有一个输入字符串。如果在输入字符串中找到大集合,它将替换为给定选项 我尝试了以下操作,但返回错误: #!/bin/python arr=['www.', 'http://', '.com', 'many many many....'] def str_replace(arr, replaceby, original): temp = '' for n,i in enumerate(arr): temp = original.replace(i, rep
#!/bin/python
arr=['www.', 'http://', '.com', 'many many many....']
def str_replace(arr, replaceby, original):
temp = ''
for n,i in enumerate(arr):
temp = original.replace(i, replaceby)
return temp
main ='www.google.com'
main1='www.a.b.c.company.google.co.uk.com'
print str_replace(arr,'',main);
输出:
www.google
预期:
google
您每次都从原始文件中导出
temp
,因此在返回的temp
中只替换arr
的最后一个元素。请尝试以下方法:
def str_replace(arr, replaceby, original):
temp = original
for n,i in enumerate(arr):
temp = temp.replace(i, replaceby)
return temp
您每次都从原始文件中导出
temp
,因此在返回的temp
中只替换arr
的最后一个元素。请尝试以下方法:
def str_replace(arr, replaceby, original):
temp = original
for n,i in enumerate(arr):
temp = temp.replace(i, replaceby)
return temp
应该是
temp = temp.replace(i, replaceby)
你在抛弃以前的替代品
应该是
temp = temp.replace(i, replaceby)
您正在丢弃以前的替换。您甚至不需要
temp
(假设以上代码是整个函数):
另一个(可能更有效)的选择是使用正则表达式:
import re
def str_replace(search, replace, subject):
search = '|'.join(map(re.escape, search))
return re.sub(search, replace, subject)
请注意,如果
replace
包含search
中的子字符串,这些函数可能会产生不同的结果,您甚至不需要temp
(假设上述代码是整个函数):
另一个(可能更有效)的选择是使用正则表达式:
import re
def str_replace(search, replace, subject):
search = '|'.join(map(re.escape, search))
return re.sub(search, replace, subject)
请注意,如果replace
包含search
中的子字符串,则这些函数可能会产生不同的结果
简单方法:)
我不明白enumerate在这里应该做什么。@Daniel:说得好,没什么。但也许OP遗漏了代码中不相关的部分,其中使用了
n
?我不明白enumerate
应该在这里做什么。@Daniel:说得好,没什么。但是,OP可能遗漏了代码中不相关的部分,其中使用了n
?对于简单的字符串替换,Regex可能效率较低。@Junuxx:请参阅中的计时。如果主题足够长,正则表达式显然比循环替换更有效。对于简单的字符串替换,正则表达式可能效率较低。@Junuxx:请参阅中的计时。只要主题足够长,Regex显然会赢得自行车替代品的青睐。