本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
從表單文檔中提取鍵值對
以下 Python 範例示範如何從Block儲存在地圖中的物件。塊對象從調用AnalyzeDocument。如需詳細資訊,請參閱 表單數據(鍵值對)。
您可以使用以下函數:
get_kv_map
— 呼叫AnalyzeDocument,並將鍵和值塊對象存儲在地圖中。get_kv_relationship
和find_value_block
— 從地圖構造鍵值關係。
從表單檔中提取鍵-值對
設定您的環境。如需詳細資訊,請參閱 先決條件。
將下列範本程式碼複製到名為的textract_python_kv_parser.py。
import boto3 import sys import re import json def get_kv_map(file_name): with open(file_name, 'rb') as file: img_test = file.read() bytes_test = bytearray(img_test) print('Image loaded', file_name) # process using image bytes client = boto3.client('textract') response = client.analyze_document(Document={'Bytes': bytes_test}, FeatureTypes=['FORMS']) # Get the text blocks blocks=response['Blocks'] # get key and value maps key_map = {} value_map = {} block_map = {} for block in blocks: block_id = block['Id'] block_map[block_id] = block if block['BlockType'] == "KEY_VALUE_SET": if 'KEY' in block['EntityTypes']: key_map[block_id] = block else: value_map[block_id] = block return key_map, value_map, block_map def get_kv_relationship(key_map, value_map, block_map): kvs = {} for block_id, key_block in key_map.items(): value_block = find_value_block(key_block, value_map) key = get_text(key_block, block_map) val = get_text(value_block, block_map) kvs[key] = val return kvs def find_value_block(key_block, value_map): for relationship in key_block['Relationships']: if relationship['Type'] == 'VALUE': for value_id in relationship['Ids']: value_block = value_map[value_id] return value_block def get_text(result, blocks_map): text = '' if 'Relationships' in result: for relationship in result['Relationships']: if relationship['Type'] == 'CHILD': for child_id in relationship['Ids']: word = blocks_map[child_id] if word['BlockType'] == 'WORD': text += word['Text'] + ' ' if word['BlockType'] == 'SELECTION_ELEMENT': if word['SelectionStatus'] == 'SELECTED': text += 'X ' return text def print_kvs(kvs): for key, value in kvs.items(): print(key, ":", value) def search_value(kvs, search_key): for key, value in kvs.items(): if re.search(search_key, key, re.IGNORECASE): return value def main(file_name): key_map, value_map, block_map = get_kv_map(file_name) # Get Key Value relationship kvs = get_kv_relationship(key_map, value_map, block_map) print("\n\n== FOUND KEY : VALUE pairs ===\n") print_kvs(kvs) # Start searching a key value while input('\n Do you want to search a value for a key? (enter "n" for exit) ') != 'n': search_key = input('\n Enter a search key:') print('The value is:', search_value(kvs, search_key)) if __name__ == "__main__": file_name = sys.argv[1] main(file_name)
在命令提示中,輸入以下命令:Replace
file
取代為您要分析的檔案圖像檔案。textract_python_kv_parser.py
file
當系統提示時,輸入輸入文檔中的鍵。如果代碼檢測到密鑰,它將顯示密鑰的值。