red*_*bia 5 python regex dictionary key normalization
假设我们有一个字典: {'Hello World': value1, 'Testing': value2}
现在我们需要在字典中查找一个词。密钥 K 需要与“Hello World”或“Testing”完全匹配才能使用。
所以让我们的text = 'hello world'我们仍然希望这个返回value1
那么我们如何处理文本与键的正则表达式匹配呢?理想情况下,我们不想遍历字典
编辑:间距方面只是一个简单的例子。文本可能会发生变化,是我们想要匹配的数字和字母的组合。我们通常会使用正则表达式模式
我愿意,
>>> d = {'Hello World': 'value1', 'Testing': 'value2'}
>>> text = 'hello world'
>>> key = next(x for x in (re.search(r'(?i)' + re.sub(r'(\s)+', r'\1', text.strip()), i) for i in d.keys()) if x).group()
>>> d[key]
'value1'
Run Code Online (Sandbox Code Playgroud)