python - 匹配 Python 字典中的不完整字符串

标签 python regex string string-matching

我有这本字典,其中键是字符串,值是整数,例如:

{
...
'X ontology entity': 0, 
'X entity': 1, 
'image quality': 10, 
'right lower kidney': 10, 
'magnetic resonance imaging': 10312, 
'MR imaging': 10312, 
 ...
}

我正在遍历该字典的键,尝试将一系列标记与这些键匹配。假设我有以下一系列标记:

MR imaging shows that the patient suffers from infection in right lower kidney.

我只是用空格分割了上面的文本。

我想匹配 MR 成像以及右下肾,因为它们是字典中的关键字。所以,我写了下面的代码,我可以用它来匹配“MR imaging”,而不是“right lower kidney”。 (请注意,键集中不存在右下角)

found = []
for i, t in enumerate(tokens):
    term = [tokens[i]]
    j = deepcopy(i)
    while (' '.join(term) in self.db_terms):
        if j < len(tokens):
            j += 1
            term.append(tokens[j])
    found.append(' '.join(term[:-1]))
return set(found)

我不知道如何通过键搜索“右下”,匹配“右下肾”,然后去检查第三个索引。

任何帮助将不胜感激!谢谢!

最佳答案

看来您正在处理 Ngram。请注意,此答案假设您的字典中有许多键而不是可能的 N-gram。在这种情况下,从文本生成 n-gram 比迭代字典键更有效(其他答案就是这种情况)。

从定义 keys 字典开始。

keys = {
'X ontology entity': 0, 
'X entity': 1, 
'image quality': 10, 
'right lower kidney': 10, 
'magnetic resonance imaging': 10312, 
'MR imaging': 10312, 
}

您需要生成一个范围内的所有 N-gram(由您决定),并且对于每个 n-gram,确定它是否作为键存在于您的字典中。

import re

def get_ngrams(tokens, ngram_range):
    return {' '.join(tokens[i:i+r]) 
        for i in range(len(tokens)) for r in range(*ngram_range)}

ngram_range = (1, 4) # Right exclusive.
tokens = re.sub(r'[^a-zA-Z]', ' ', text).split()
found_tokens = set(filter(keys.__contains__, get_ngrams(tokens, ngram_range)))

print(found_tokens)
# {'MR imaging', 'right lower kidney'}

请记住,对于更大的范围和字符串,这将成为一项昂贵的操作。


您可以通过认识到并非所有 N 元语法都需要在过滤前存储在内存中来进行一些优化。我们可以使用生成器和循环节省大量时间:

def ngrams_generator(tokens, ngram_range):
    yield from (' '.join(tokens[i:i+r]) 
        for i in range(len(tokens)) for r in range(*ngram_range))

found_ngrams = set()
for ngram in ngrams_generator(tokens, ngram_range):
    if ngram in keys:
        found_ngrams.add(ngram)

print(found_ngrams)
# {'MR imaging', 'right lower kidney'}

关于python - 匹配 Python 字典中的不完整字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53551527/

相关文章:

python - 在 python 中使用 Netcdf4 从 Netcdf 文件中检索 float32 时出现 ValueError 字符串 float

regex - Sublime Text : Regex to convert Uppercase to Title Case?

string - 在 while 循环中使用 hasNextInput() 它为给定的每个字符串提供循环,但我希望它提示一次

c - C中从文件中读取字符串输入

Python 和 Django - 如何在内存和临时文件中使用

python - 对 pandas 数据框中的条目进行分组

java - 使用正则表达式解析此日期时间字符串

regex - 如何使用正则表达式和 sed (或等效的 unix 命令行工具)来修复 LaTeX 标题中的标题大小写?

java - Java 中迭代从 'One' String 到 'Another' String 的字符串列表

python - 开放堆栈。 "No valid host was found"对于 cirrOS 以外的任何图像