我正在尝试将我的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语句。
答案 0 :(得分:1)
您可以删除所有“特殊字符/空格”并比较值:
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