【问题标题】:Python function to find similarity between differently formatted strings用于查找不同格式字符串之间相似性的 Python 函数
【发布时间】:2018-05-19 11:49:32
【问题描述】:

我有 2 个带有项目名称的 excel 文件。我想比较这些项目,但唯一远程相似的列是名称列,它也具有不同的名称格式,例如

儿童钢琴作为儿童钢琴

Butter Gel 100mg as Butter-Gel-100MG

我知道它不可能 100% 准确,所以我会要求操作代码的人进行最终验证,但我如何显示最接近的匹配名称?

【问题讨论】:

    标签: python string python-3.x formatting substring


    【解决方案1】:

    这样做的正确方法是编写正则表达式。

    但下面的普通代码也可以解决问题:

    column_a = ["KIDS-Piano", "Butter Gel 100mg"]
    column_b = ["kids piano", "Butter-Gel-100MG"]
    
    new_column_a = []
    for i in column_a:
        # convert strings into lowercase
        a = i.lower()
        # replace dashes with spaces
        a = a.replace('-', ' ')
        new_column_a.append(a)
    
    # do the same for column b
    new_column_b = []
    for i in column_b:
        # convert strings into lowercase
        a = i.lower()
        # replace dashes with spaces
        a = a.replace('-', ' ')
        new_column_b.append(a)
    
    as_not_found_in_b = []
    for i in new_column_a:
        if i not in new_column_b:
            as_not_found_in_b.append(i)
    
    bs_not_found_in_a = []
    for i in new_column_b:
        if i not in new_column_a:
            bs_not_found_in_a.append(i)
    
    # find the problematic ones and manually fix them
    print(as_not_found_in_b)
    print(bs_not_found_in_a)
    

    【讨论】:

    • 感谢@Gnoliz 我做了类似的事情,但正如你所说,我使用 RE by re.findall(r"[\w]+", lst.lower()) 接受了这些词
    猜你喜欢
    • 2019-04-18
    • 2015-10-23
    • 2019-01-29
    • 2019-01-26
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 2013-09-08
    相关资源
    最近更新 更多