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', '.']