Python - 如何匹配和替换给定字符串中的单词?

时间:2012-06-07 10:50:07

标签: python python-2.7

我有一个包含大集合的数组列表,我有一个输入字符串。如果在输入字符串中找到大的collecion,它将被给定的选项替换。

我试过跟随但它的错误回复:

#!/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

4 个答案:

答案 0 :(得分:4)

您每次都会从原始内容中获取temp,因此只有arr的最后一个元素会在返回的temp中被替换。试试这个:

def str_replace(arr, replaceby, original):
  temp = original
  for n,i in enumerate(arr):
    temp = temp.replace(i, replaceby)
  return temp

答案 1 :(得分:3)

您甚至不需要temp(假设上面的代码是整个函数):

def str_replace(search, replace, subject):
    for s in search:
        subject = subject.replace(s, replace)
    return subject

另一个(可能更有效)选项是使用正则表达式:

import re

def str_replace(search, replace, subject):
    search = '|'.join(map(re.escape, search))
    return re.sub(search, replace, subject)

请注意,如果replace包含来自search的子字符串,这些函数可能会产生不同的结果。

答案 2 :(得分:2)

temp = original.replace(i, replaceby)

应该是

temp = temp.replace(i, replaceby)

你丢掉了之前的替换品。

答案 3 :(得分:2)

简单方法:)

arr=['www.', 'http://', '.com', 'many many many....']
main ='http://www.google.com'
for item in arr:
    main = main.replace(item,'')
print main