python - 如何在忽略特殊字符和空格的情况下将字符串与另一个字符串匹配?
问题描述
我正在尝试将我的 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语句。
解决方案
您可以删除所有“特殊字符/空格”并比较值:
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
推荐阅读
- python - 如何在 Tkinter 中显示调整后的 PIL 图像?
- ruby-on-rails - 如何确认对象是否在 rails-for-API 中被删除?
- node.js - 具有依赖项的 Nestjs 中间件
- delphi - 如何使用 SynCrypto 加密大文件?
- c++ - 为什么在创建右值并将其传递给函数时会有副本?
- javascript - 如何从 Material UI 日期时间选择器中删除分钟按钮
- firebase - 如何解决此问题 [错误:flutter/lib/ui/ui_dart_state.cc(199)] 未处理的异常:NoSuchMethodError:getter 'phone' 被调用为 null。错误?
- java - 来自 openapi-generator 的 jaxrs-resteasy 生成器操作给定的示例
- foreign-keys - 如何向 Google Data Studio Blend 添加外键
- java - 是否有类似的替代 Python 的用于 Java 的泡菜模块?