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

