要解决“AWS Textract PDF转JSON键值对的困惑”,您可以按照以下步骤进行操作:
安装AWS SDK:确保您已安装AWS SDK,并在代码中引入适当的模块。
创建AWS Textract客户端:使用AWS SDK创建Textract客户端,以便与AWS Textract服务进行交互。
import boto3
# 创建Textract客户端
textract_client = boto3.client('textract', region_name='your_region')
# 启动Textract任务
response = textract_client.start_document_text_detection(
DocumentLocation={
'S3Object': {
'Bucket': 'your_bucket_name',
'Name': 'your_file_key.pdf'
}
}
)
# 获取任务ID
job_id = response['JobId']
import time
# 轮询获取任务状态
while True:
response = textract_client.get_document_text_detection(JobId=job_id)
status = response['JobStatus']
if status in ['SUCCEEDED', 'FAILED']:
break
# 等待一段时间再继续轮询
time.sleep(5)
# 获取API响应中的Blocks
blocks = response['Blocks']
# 提取键值对
key_value_pairs = []
for block in blocks:
if block['BlockType'] == 'KEY_VALUE_SET':
key_value_pairs.append({
'Key': block['Key']['Text'],
'Value': block['Value']['Text']
})
# 打印键值对
for pair in key_value_pairs:
print(pair['Key'], pair['Value'])
这是一个基本的解决方案示例,您可以根据自己的需求进行修改和扩展。确保替换代码中的占位符,如"your_region"、"your_bucket_name"和"your_file_key.pdf",以适应您的实际情况。