过滤重复的字词

很多时候,需要仅针对文件中存在的唯一单词分析文本。 因此,我们需要从文本中删除重复的单词 这是通过使用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', '.']

上一篇:向后读取文件

下一篇:提取电子邮件地址

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程