Python – 过滤重复词汇
很多时候,我们要分析文本中仅出现一次的词语。所以,我们需要从文本中消除重复的单词。这可以通过在nltk中使用词汇标记和集合函数来实现。
不保留顺序
在以下示例中,我们首先将句子分词为单词。然后我们应用set()函数,它创建一个无序的独特元素集合。结果是独特的单词,它们没有排序。
import nltk
word_data = "The Sky is blue also the ocean is blue also Rainbow has a blue colour."
# 首先进行单词分词
nltk_tokens = nltk.word_tokenize(word_data)
# 应用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."
# 首先进行单词分词
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', '.']