2

例えば:

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

をフィルターで除外できるようにしたいので、次のdogようcatになります。

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に含まれているかどうかのチェックを削除しましたwreplace

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 に答える