2

例如:

item =['the dog is gone', 'the dog and cat is gone']
words= ['dog','cat'] 

我希望能够过滤掉dogcat所以它会显示:

item=['the  is gone', 'the   and  is gone']

item1=[] 
for w in words:
   for line in item:
      if w in line:
         j=gg.replace(it,'')
         item1.append(j)

我得到以下信息:

['the  is gone', 'the cat and  is gone', 'the  and dog is gone']
4

2 回答 2

5

您正在遍历每个单词的所有行并附加替换。您应该切换这些循环:

item1 = [] 
for line in item:
    for w in words:
        line = line.replace(w, '')
    item1.append(line)

注意:我更改了一些代码

  • 改为gg_line
  • 改为it_item
  • 删除了检查是否line包含w,因为它由replace

replace不知道单词边界。如果您只想删除整个单词,您应该尝试不同的方法。使用re.sub

import re

item1 = [] 
for line in item:
    for w in words:
        line = re.sub(r'\b%s\b' % w, '', line)  # '\b' is a word boundry
    item1.append(line)
于 2012-12-01T06:16:54.000 回答
2

您可以改用这种方法:

item =['the dog is gone', 'the dog and cat is gone']
words= ['dog','cat'] 

item2 = [" ".join([w for w in t.split() if not w in words]) for t in item]

print item2

>>> ['the is gone', 'the and is gone']
于 2014-07-08T08:13:18.767 回答