如何从文本文件中提取自定义实体列表?

问题描述

我有一个看起来像这样的实体列表:

["Bluechoice HMO/POS","Pathway X HMO/PPO","HMO","Indemnity/Traditional Health Plan/Standard"]

这不是详尽的列表,还有其他类似的条目。

我想从文本文件(超过 30 页的信息)中提取这些实体(如果存在)。这里的关键是这个文本文件是使用 OCR 生成的,因此可能不包含确切的条目。也就是说,例如,它可能有:

"Out of all the entries the user made,BIueChoise HMOIPOS is the most prominent"

注意“BIueChoise HMIPOS”中的拼写错误 w.r.t. “Bluechoice HMO/POS”。

我想要那些出现在文本文件中的实体,即使相应的词不完全匹配。

欢迎任何帮助,无论是算法还是方法。非常感谢!

解决方法

您可以使用可以近似匹配字符串并确定它们的相似程度的算法来实现这一点,例如 Levenshtein distanceHamming distanceCosine similarity 等等。

textdistance 是一个模块,其中包含可供您使用的多种此类算法。检查一下here

我遇到了类似的问题,我使用 textdistance 从长度等于我需要搜索/提取的字符串的文本文件中选取子字符串解决了这个问题,然后使用其中一种算法来查看哪种算法可以解决我的问题。 对我来说,当我过滤掉模糊匹配高于 75% 的字符串时,余弦相似度 给了我最好的结果。

以您的问题中的“Bluechoice HMO/POS”为例给您一个想法,我将其应用如下:

>>> import textdistance
>>>
>>> search_strg = "Bluechoice HMO/POS"
>>> text_file_strg = "Out of all the entries the user made,BIueChoise HMOIPOS is the most prominent"
>>>
>>> extracted_strgs = []
>>> for substr in [text_file_strg[i:i+len(search_strg)] for i in range(0,len(text_file_strg) - len(search_strg)+1)]:
...     if textdistance.cosine(substr,search_strg) > 0.75:
...             extracted_strgs.append(substr)
... 
>>> extracted_strgs
['BIueChoise HMOIPOS']