首页 > 解决方案 > 列表中的重复字符串不会被删除,除非最相似的字符串在子列表中

问题描述

无法成功删除包含文本字符串(报纸文章全文)的列表。唯一的解决方案是找到最常见的句子,选择包含这些句子的列表项,然后在这些子列表级别进行重复数据删除。

在阅读了无数类似的问题后,我仍然没有解决方案。

以下是我尝试过的四种不同方法:

1] x = list(dict.fromkeys(lst))
2] x = set(lst)
3] from iteration_utilities import unique_everseen
   x = list(unique_everseen(lst))
4] using pandas
   df = df.drop_duplicates(subset=['article_body'], keep='first')

所有这些都返回相同数量的列表项。

但是,当我检查最常见的“句子”的频率分布并搜索一个时。我仍然发现大约 45 个命中,因为这句话出现在几个文本中,其中一些是相同的。当这些文本都集中到一个列表中时,我可以使用 x = list(dict.fromkeys(lst))。这导致只有 9 个列表项。

这怎么可能?

df = pd.read_json('UK data/2010-11.json')
len(df)
13288

df = df.drop_duplicates(subset=['article_body'], keep='first')
len(df)
6118

lst = df['article_body'].tolist()
len(lst)
6118

# taking this solution as a reference point, here it returns 6118 at the level
# of the whole list

len(list(dict.fromkeys(lst)))
6118

from nltk.tokenize import sent_tokenize

searchStr = 'Lines close at midnight.'
found = []

for text in lst:
    sentences = sent_tokenize(text)
    for sentence in sentences:
        if sentence == searchStr:
            found.append(text)

len(found)
45

# when the function is used only on a subset of the full-texts, it can suddenly 
# identify more duplicates

len(list(dict.fromkeys(found)))
9

编辑:请在此处查看 jupyter notebook 中的完整演示: https ://colab.research.google.com/drive/1EF6PL8aduZIO--Ok0hGMzLWFIquz6F_L

我希望在完整列表中使用相同的函数会导致删除所有重复项,但显然情况并非如此。为什么我不能从整个列表中删除重复项?我如何确保将每个列表项与所有其他项进行比较?

标签: pythonstringnlpduplicates

解决方案


听起来空格可能是问题所在。

import re

x = list(set(map(lambda string: re.sub(r'\s+', ' ', string), lst)))

或类似的东西可能会起作用。


推荐阅读