[英]Python - How to match and replace words from a given string?
I have a array list with large collection, and i have one input string. 我有一个包含大量集合的数组列表,并且我有一个输入字符串。 Large collecion if found in the input string, it will replace by given option.
如果在输入字符串中找到较大的集合,它将被给定的选项替换。
I tried following but its returning wrong: 我尝试了以下操作,但返回错误:
#!/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);
Output: 输出:
www.google
Expected: 预期:
google
You are deriving temp
from the original every time, so only the last element of arr
will be replaced in the temp
that is returned. 您每次都是从原始
temp
派生temp
,因此在返回的temp
中只会替换arr
的最后一个元素。 Try this instead: 尝试以下方法:
def str_replace(arr, replaceby, original):
temp = original
for n,i in enumerate(arr):
temp = temp.replace(i, replaceby)
return temp
You don't even need temp
(assuming the above code is the whole function): 您甚至不需要
temp
(假设上面的代码是整个函数):
def str_replace(search, replace, subject):
for s in search:
subject = subject.replace(s, replace)
return subject
Another (probably more efficient) option is to use regular expressions: 另一个(可能更有效)的选择是使用正则表达式:
import re
def str_replace(search, replace, subject):
search = '|'.join(map(re.escape, search))
return re.sub(search, replace, subject)
Do note that these functions may produce different results if replace
contains substrings from search
. 请注意,如果
replace
包含search
子字符串,这些函数可能会产生不同的结果。
temp = original.replace(i, replaceby)
It should be 它应该是
temp = temp.replace(i, replaceby)
You're throwing away the previous substitutions. 您将放弃以前的替代方法。
Simple way :) 简单的方法:)
arr=['www.', 'http://', '.com', 'many many many....']
main ='http://www.google.com'
for item in arr:
main = main.replace(item,'')
print main
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.