python删除重复单词_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', '.']

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值