从具有不同结构的窗体中提取字段

2024-05-11 10:36:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图从资产负债表中提取某些字段。例如,我想知道以下资产负债表的“库存”值为1277838:

Balance sheet

目前,我正在使用Tesseract将图像转换为文本。但是,这种转换会导致文本流,因此很难将字段与其值关联(因为这些值并不总是紧靠其对应字段的文本)。

经过一番搜索,我阅读了Tesseract可以使用uzn文件从一幅图像的区域读取。然而,资产负债表价值的特定区域可能会从一种形式转移到另一种形式,因此我对任何可以确定“库存”和1277838在同一条线上的解决方案感兴趣。理想情况下,我想要一个文本的网格结构输出(这样我就可以从空间上判断哪些文本块在同一行/列中)。

有谁能帮我解释一下我是怎么做到这一点的?


Tags: 文件图像文本区域库存资产解决方案感兴趣
2条回答

正如gaw89已经提到的,Tesseract可以输出比仅将文本作为流更多的信息。hocr fileformat还提供了每个段落、行、词的位置(边界框):

$ tesseract 4LV05.png out -l eng hocr

例如,您可以通过简单的

$ grep 'Inventory' out.hocr
 <span class='ocr_line' id='line_1_5' title="bbox 23 183 112 204; baseline 0 -5; x_size 21; x_descenders 5; x_ascenders 4"><span class='ocrx_word' id='word_1_15' title='bbox 23 183 112 204; x_wconf 93'>Inventory</span>

因此,这个词的边界框从183到204垂直跨越,对于这个标签的相应值,我们现在必须在相同的垂直空间中搜索框。例如,这可以通过

$ grep 'bbox [0-9]* 18[0-9]' out.hocr
<p class='ocr_par' id='par_1_4' lang='eng' title="bbox 23 183 112 204">
 <span class='ocr_line' id='line_1_5' title="bbox 23 183 112 204; baseline 0 -5; x_size 21; x_descenders 5; x_ascenders 4"><span class='ocrx_word' id='word_1_15' title='bbox 23 183 112 204; x_wconf 93'>Inventory</span>
 <span class='ocr_line' id='line_1_30' title="bbox 1082 183 1178 202; baseline 0 -3; x_size 22; x_descenders 5.5; x_ascenders 5.5"><span class='ocrx_word' id='word_1_82' title='bbox 1082 183 1178 202; x_wconf 93'>1,277,838</span>
 <span class='ocr_line' id='line_1_54' title="bbox 1301 183 1379 202; baseline 0 -3; x_size 22; x_descenders 5.5; x_ascenders 5.5"><span class='ocrx_word' id='word_1_107' title='bbox 1301 183 1379 202; x_wconf 95'>953,675</span>

第二个结果包含目标值。您可以比较bbox的垂直坐标,以确保提取第一列。

在本例中,命令grep已经足够了,但是肯定有其他方法可以做类似的事情。还要注意,正则表达式可能应该替换为其他一些计算,这取决于页面的倾斜程度。

或者,您可以尝试使用开源的Tabula,它将尝试从pdf中提取表格数据。

我一直在使用Tesseract和Python(pytesseract库)执行类似的任务。我已经能够使用Tesseract的.hocr输出文件(https://en.wikipedia.org/wiki/HOCR)在页面上找到我的搜索词(例如“Inventory”)的位置,然后在页面的一个小部分上重新运行Tesseract,这使它对该区域的精度更高。下面是我用来分析来自Tesseract的HOCR输出的代码:

def parse_hocr(search_terms=None, hocr_file=None, regex=None):
    """Parse the hocr file and find a reasonable bounding box for each of the strings
    in search_terms.  Return a dictionary with values as the bounding box to be used for 
    extracting the appropriate text.

    inputs:
        search_terms = Tuple, A tuple of search terms to look for in the HOCR file.

    outputs:
        box_dict = Dictionary, A dictionary whose keys are the elements of search_terms and values
        are the bounding boxes where those terms are located in the document.
    """
    # Make sure the search terms provided are a tuple.
    if not isinstance(search_terms,tuple):
        raise ValueError('The search_terms parameter must be a tuple')

    # Make sure we got a HOCR file handle when called.
    if not hocr_file:
        raise ValueError('The parser must be provided with an HOCR file handle.')

    # Open the hocr file, read it into BeautifulSoup and extract all the ocr words.
    hocr = open(hocr_file,'r').read()
    soup = bs.BeautifulSoup(hocr,'html.parser')
    words = soup.find_all('span',class_='ocrx_word')

    result = dict()

    # Loop through all the words and look for our search terms.        
    for word in words:

        w = word.get_text().lower()

        for s in search_terms:

            # If the word is in our search terms, find the bounding box
            if len(w) > 1 and difflib.SequenceMatcher(None, s, w).ratio() > .5:
                bbox = word['title'].split(';')
                bbox = bbox[0].split(' ')
                bbox = tuple([int(x) for x in bbox[1:]])

                # Update the result dictionary or raise an error if the search term is in there twice.
                if s not in result.keys():
                    result.update({s:bbox})

            else:
                pass

    return result 

这允许我在HOCR文件中搜索合适的词并返回该词的边界框。然后,我可以稍微展开边界框,在页面的一个非常小的子集上运行Tesseract。这比仅仅对整个页面进行ocr处理要精确得多。显然,有些代码是我特别使用的,但它应该给你一个开始的地方。

This page对于找到要给Tesseract的适当参数非常有帮助。我发现页面分割模式对于获得图像小部分的准确结果非常重要。

相关问题 更多 >