Python文本处理

过滤重复的字词

过滤重复的字词详细操作教程
很多时候,需要仅针对文件中存在的唯一单词分析文本。 因此,我们需要从文本中删除重复的单词 这是通过使用nltk中可用的单词标记化和集合功能来实现的。

不保留顺序

在下面的例子中,我们首先将句子标记为单词。 然后应用set()函数创建一个无序的唯一元素集合。结果一个不排序的唯一单词。
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-23
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
当执行上面代码,得到以下结果 -
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-23
['blue', 'Rainbow', 'is', 'Sky', 'colour', 'ocean', 'also', 'a', '.', 'The', 'has', 'the']

保留顺序

要在删除重复项之后获取单词但仍然保留句子中单词的顺序,我们将读取单词并通过附加单词将其添加到列表中。
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-23
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
当执行上面代码,得到以下结果 -
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-23
['The', 'Sky', 'is', 'blue', 'also', 'the', 'ocean', 'Rainbow', 'has', 'a', 'colour', '.']
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4