Python - 過濾重複單詞



很多時候,我們需要分析文字,只需要瞭解該檔案中存在的唯一單詞。因此,我們需要從文字中去除重複單詞。我們需要使用 nltk 中可用的單詞標記化和集合函式,才能實現這一點。

不保留順序

在下面的示例中,我們首先將句子標記為詞語。然後,我們應用 create() 函式,該函式建立一個獨一無二元素的無序集合。結果包含唯一的單詞,不按順序排列。

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', '.']
廣告
© . All rights reserved.