1

タグ付けされたバイグラムをたくさん含むリストがあります。一部のバイグラムは正しくタグ付けされていないため、マスター リストから削除したいと考えています。バイグラムの単語の 1 つが頻繁に繰り返されるため、バイグラムに xyz 単語が含まれている場合は削除できます。疑似例は以下のとおりです。

master_list = ['this is', 'is a', 'a sample', 'sample word', 'sample text', 'this book', 'a car', 'literary text', 'new book', 'them about', 'on the' , 'in that', 'tagged corpus', 'on top', 'a car', 'an orange', 'the book', 'them what', 'then how']

unwanted_words = ['this', 'is', 'a', 'on', 'in', 'an', 'the', 'them']

new_list = [item for item in master_list if not [x for x in unwanted_words] in item]

アイテムを個別に削除できます。つまり、リストを作成して、「on」などの単語を含むアイテムを削除するたびに削除できます。これは面倒で、何時間ものフィルタリングと不要な単語をフィルタリングするための新しいリストの作成が必要になります。ループが役立つと思いました。ただし、次のタイプのエラーが発生します。

Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
new_list = [item for item in master_list if not [x for x in  unwanted_words] in item]
File "<pyshell#21>", line 1, in <listcomp>
new_list = [item for item in master_list if not [x for x in unwanted_words] in item]
TypeError: 'in <string>' requires string as left operand, not list

あなたの助けは大歓迎です!

4

1 に答える 1

1

条件if not [x for x in unwanted_words] in itemは と同じです。つまり、リストが文字列に含まれているif not unwanted_words in itemかどうかをチェックしています。

代わりに、 を使用anyして、バイグラムのいずれかの部分が に含まれているかどうかを確認できますunwanted_words。また、ルックアップを高速化するために を作成unwanted_wordsすることもできます。set

>>> master_list = ['this is', 'is a', 'a sample', 'sample word', 'sample text', 'this book', 'a car', 'literary text', 'new book', 'them about', 'on the' , 'in that', 'tagged corpus', 'on top', 'a car', 'an orange', 'the book', 'them what', 'then how']
>>> unwanted_words = set(['this', 'is', 'a', 'on', 'in', 'an', 'the', 'them'])
>>> [item for item in master_list if not any(x in unwanted_words for x in item.split())]
['sample word', 'sample text', 'literary text', 'new book', 'tagged corpus', 'then how']
于 2015-03-21T22:47:32.700 に答える