📜  Python过滤重复单词

📅  最后修改于: 2020-11-06 06:15:40             🧑  作者: Mango


很多时候,我们只需要分析文件中存在的唯一单词的文本即可。因此,我们需要从文本中消除重复的单词。这可以通过使用nltk中的单词标记化和set函数来实现。

不保留订单

在下面的示例中,我们首先将句子标记为单词。然后,我们使用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', '.']