要解决 AWS Textract 无法识别 PDF 文档的第二页的表格的问题,可以使用以下代码示例:
import boto3
# 创建 Textract 客户端
textract_client = boto3.client('textract')
def extract_table_from_pdf(pdf_s3_bucket, pdf_s3_object_key):
# 构建请求参数
start_page = 2 # 设置开始页码为第二页
end_page = 2 # 设置结束页码为第二页
feature_types = ['TABLES'] # 设置要提取的特征类型为表格
# 发起 Textract 分析请求
response = textract_client.start_document_analysis(
DocumentLocation={
'S3Object': {
'Bucket': pdf_s3_bucket,
'Name': pdf_s3_object_key
}
},
FeatureTypes=feature_types,
StartPage=start_page,
EndPage=end_page
)
# 获取分析任务的标识符
job_id = response['JobId']
# 等待分析任务完成
while True:
response = textract_client.get_document_analysis(JobId=job_id)
status = response['JobStatus']
if status in ['SUCCEEDED', 'FAILED']:
break
if status == 'SUCCEEDED':
# 提取表格结果
tables = []
for page_result in response['Blocks']:
if page_result['BlockType'] == 'TABLE':
table = []
for relationship in page_result['Relationships']:
if relationship['Type'] == 'CHILD':
for child_id in relationship['Ids']:
child = response['Blocks'][child_id]
if child['BlockType'] == 'CELL':
table.append(child['Text'])
tables.append(table)
return tables
else:
# 分析任务失败
print(f"分析任务失败:{response['StatusMessage']}")
return None
# 使用示例
pdf_s3_bucket = 'your-pdf-s3-bucket'
pdf_s3_object_key = 'your-pdf-s3-object-key'
tables = extract_table_from_pdf(pdf_s3_bucket, pdf_s3_object_key)
if tables:
for table in tables:
print(table)
else:
print("无法提取表格。")
在上述代码中,我们使用 start_document_analysis
方法发起 Textract 分析任务,并通过指定 StartPage
和 EndPage
参数来指定要分析的页码范围。在本例中,我们将 StartPage
和 EndPage
都设置为 2,即只分析第二页。
同时,我们还设置 FeatureTypes
参数为 ['TABLES']
,表示只提取表格特征。根据实际需要,您可以调整这些参数以满足您的需求。
在分析任务完成后,我们从分析结果中提取表格数据,并返回一个包含所有表格的列表。
请确保您已正确配置 AWS 身份验证凭证,并将正确的 PDF 文件的 S3 存储桶和对象键传递给 extract_table_from_pdf
函数。
注意:有时 Textract 可能无法正确识别表格,特别是对于复杂的表格布局。在这种情况下,您可以尝试调整 Textract 的分析参数或使用其他工具进行表格提取。