删除同一列中的部分重复项,同时保留较长的文本?

2024-05-26 17:43:51 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我是Python新手,希望删除同一列中部分相似的条目。例如,这些是数据帧中一列中的条目-

第一排-“我有你们的沐浴露,我想知道它是否含有动物成分。还有,哪些动物成分?我不喜欢使用含有动物成分的产品。”

第二排——“上面也没有ADA。这是假的牙膏,是你的仿制品吗?”

第3行-“我有你们的沐浴液,我想知道它是否含有动物成分。我不喜欢使用含有动物成分的产品。”

第4行-“我没有看到这个盒子上的ADA印章。我只是想确保它仍然可以安全使用?”

第5排-“你好,我只是想知道新牙膏是否经美国牙科协会批准?包装上没有注明”

第6排-“你好,我只是想知道新牙膏是否经ADA批准?盒子上没有写。”

因此,在本列中,第1行&;第3行和第5行&;6个相似(部分重复)。我希望python能够识别这些重复的语句,保留较长的语句,删除较短的语句,并将新数据导出到csv文件中

预期产量- 第一排-“我有你们的沐浴露,我想知道它是否含有动物成分。还有,哪些动物成分?我不喜欢使用含有动物成分的产品。”

第二排——“上面也没有ADA。这是假的牙膏,是你的仿制品吗?”

第3排-“我没有在这个盒子上看到美国残疾人协会的印章。我只是想确保它仍然可以安全使用?”

第4排-“你好,我只是想知道新牙膏是否经美国牙科协会批准?包装上没有注明”

我尝试使用fuzzyfuzzy,其中我使用了相似性排序函数,但它没有给我预期的输出。有没有更简单的代码


Tags: 数据产品条目语句盒子amp协会成分
1条回答
网友
1楼 · 发布于 2024-05-26 17:43:51

这是我的方法,希望评论是不言自明的

from fuzzywuzzy import fuzz,process

rows = ["I have your Body Wash and I wonder if it contains animal ingredients. Also, which animal ingredients? I prefer not to use product with animal ingredients.","This also doesn't have the ADA on there. Is this a fake toothpaste an imitation of yours?","I have your Body Wash and I wonder if it contains animal ingredients. I prefer not to use product with animal ingredients.","I didn't see the ADA stamp on this box. I just want to make sure it was still safe to use?","Hello, I was just wondering if the new toothpaste is ADA approved? It doesn’t say on the packaging","Hello, I was just wondering if the new toothpaste is ADA approved? It doesn’t say on the box."]

clean = []
threshold = 80 # this is arbitrary
for row in rows:
    # score each sentence against each other sentence
    # [('string', score),..]
    scores = process.extract(row, rows, scorer=fuzz.token_set_ratio)
    # basic idea is if there is a close second match we want to evaluate 
    # and keep the longer of the two
    if scores[1][1] > threshold:
        clean.append(max([x[0] for x in scores[:2]],key=len))
    else:
        clean.append(scores[0][0])
# remove dupes
clean = set(clean)

相关问题 更多 >

    热门问题