Python-text-processing-python-filter-duplicate-words
提供:Dev Guides
Python-重複する単語をフィルタリングする
多くの場合、ファイルに存在する一意の単語についてのみテキストを分析する必要があります。 そのため、テキストから重複する単語を削除する必要があります。 これは、nltkで使用可能なトークン化と設定関数を使用することで実現されます。
順序を維持せずに
以下の例では、まず文を単語にトークン化します。 次に、一意の要素の順序なしコレクションを作成するset()関数を適用します。 結果には、順序付けられていない一意の単語が含まれています。
import nltk
word_data = "The Sky is blue also the ocean is blue also Rainbow has a blue colour."
# First Word tokenization
nltk_tokens = nltk.word_tokenize(word_data)
# Applying Set
no_order = list(set(nltk_tokens))
print no_order
上記のプログラムを実行すると、次の出力が得られます-
['blue', 'Rainbow', 'is', 'Sky', 'colour', 'ocean', 'also', 'a', '.', 'The', 'has', 'the']
順序を維持する
重複を削除した後でも単語を取得するために、文中の単語の順序を維持するために、単語を読み、追加してリストに追加します。
import nltk
word_data = "The Sky is blue also the ocean is blue also Rainbow has a blue colour."
# First Word tokenization
nltk_tokens = nltk.word_tokenize(word_data)
ordered_tokens = set()
result = []
for word in nltk_tokens:
if word not in ordered_tokens:
ordered_tokens.add(word)
result.append(word)
print result
上記のプログラムを実行すると、次の出力が得られます-
['The', 'Sky', 'is', 'blue', 'also', 'the', 'ocean', 'Rainbow', 'has', 'a', 'colour', '.']