文字列から一般的な単語(およびその複数形)を削除するテクニック 質問する

文字列から一般的な単語(およびその複数形)を削除するテクニック 質問する

長いテキスト文字列を解析して、レシピのタグ (キーワード) を見つけようとしています。テキストには、レシピの材料、手順、短い説明が含まれています。

タグリストから一般的な単語を削除する最も効率的な方法は何だと思いますか?

一般的な単語とは、「the」、「at」、「there」、「their」などの単語を指します。

使用できる方法は 2 つありますが、速度の面でどちらがより効率的だと思いますか。また、これを実行できるより効率的な方法をご存知ですか。

方法論 1:
- 各単語の出現回数を決定する (ライブラリコレクションを使用)
- 一般的な単語のリストを用意し、コレクションオブジェクトからそのキーが存在する場合は削除して、コレクションオブジェクトからすべての「一般的な単語」を削除します。
- したがって、速度は変数区切りの長さによって決まります。

import collections from Counter
delim     = ['there','there\'s','theres','they','they\'re'] 
# the above will end up being a really long list!
word_freq = Counter(recipe_str.lower().split())
for delim in set(delims):
    del word_freq[delim]
return freq.most_common()

方法 2:
- 複数形になる可能性のある一般的な単語については、レシピ文字列内の各単語を調べ、一般的な単語の複数形ではないバージョンが部分的に含まれていないかどうかを確認します。例: 文字列「There's a test」の場合、各単語に「there」が含まれているかどうかを確認し、含まれている場合は削除します。

delim         = ['this','at','them'] # words that cant be plural
partial_delim = ['there','they',] # words that could occur in many forms
word_freq     = Counter(recipe_str.lower().split())
for delim in set(delims):
    del word_freq[delim]
# really slow 
for delim in set(partial_delims):
    for word in word_freq:
        if word.find(delim) != -1:
           del word_freq[delim]
return freq.most_common()

ベストアンサー1

私は次のようにします:

from nltk.corpus import stopwords
s=set(stopwords.words('english'))

txt="a long string of text about him and her"
print filter(lambda w: not w in s,txt.split())

印刷する

['long', 'string', 'text']

ハッシュ セットの検索が O(1) であると考えると、複雑さの点では、文字列内の単語数は O(n) になるはずです。

ちなみに、私のバージョンのNLTKでは127を定義していますストップワード:

'all', 'just', 'being', 'over', 'both', 'through', 'yourselves', 'its', 'before', 'herself', 'had', 'should', 'to', 'only', 'under', 'ours', 'has', 'do', 'them', 'his', 'very', 'they', 'not', 'during', 'now', 'him', 'nor', 'did', 'this', 'she', 'each', 'further', 'where', 'few', 'because', 'doing', 'some', 'are', 'our', 'ourselves', 'out', 'what', 'for', 'while', 'does', 'above', 'between', 't', 'be', 'we', 'who', 'were', 'here', 'hers', 'by', 'on', 'about', 'of', 'against', 's', 'or', 'own', 'into', 'yourself', 'down', 'your', 'from', 'her', 'their', 'there', 'been', 'whom', 'too', 'themselves', 'was', 'until', 'more', 'himself', 'that', 'but', 'don', 'with', 'than', 'those', 'he', 'me', 'myself', 'these', 'up', 'will', 'below', 'can', 'theirs', 'my', 'and', 'then', 'is', 'am', 'it', 'an', 'as', 'itself', 'at', 'have', 'in', 'any', 'if', 'again', 'no', 'when', 'same', 'how', 'other', 'which', 'you', 'after', 'most', 'such', 'why', 'a', 'off', 'i', 'yours', 'so', 'the', 'having', 'once'

もちろん、独自のセットを提供することもできます。質問に対するコメントに同意します。つまり、削除したいバリエーションをすべて最初に提供するのがおそらく最も簡単 (かつ最速) です。ただし、これよりも多くの単語を削除したい場合は別ですが、その場合は、不必要な単語を削除するよりも、興味深い単語を見つける方が問題になります。

おすすめ記事