過濾重複的字詞


很多時候,需要僅針對檔案中存在的唯一單詞分析文字。 因此,我們需要從文字中刪除重複的單詞 這是通過使用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', '.']