首页 > 解决方案 > 如何在忽略特殊字符和空格的情况下将字符串与另一个字符串匹配?

问题描述

我正在尝试将我的 python 代码中的 json 文件的值与同一代码本身中另一个 API 调用的另一个值匹配。值基本相同,但不匹配,因为有时特殊字符或尾随/结尾空格会导致问题

比方说:

第一个 json 文件中的值:

json1['org'] = google, LLC    

第二个 json 文件中的值:

json2['org'] = Google-LLC

尝试在代码中使用in运算符,但它不起作用。我不确定如何将正则表达式灌输到这个中。

所以我写了if这样的声明:

if json1['org'] in json2['org']:
    # *do something*
else:
    # _do the last thing_

即使它们相同,它也会继续跳到 else 语句上。

如果无论特殊字符和空格如何,json值都相同,则应匹配并输入if语句。

标签: pythonjsonapi

解决方案


您可以删除所有“特殊字符/空格”并比较值:

import string
asciiAndNumbers = string.ascii_letters + string.digits

json1 = {'org': "google, LLC"}
json2 = {'org': "Google-LLC"}


def normalizedText(text):
    # We are just allowing a-z, A-Z and 0-9 and use lowercase characters
    return ''.join(c for c in text if c in asciiAndNumbers).lower()

j1 = normalizedText(json1['org'])
j2 = normalizedText(json2['org'])

print (j1)
print (j1 == j2)

印刷:

googlellc
True

推荐阅读