# coding:utf8 import re from typing import Dict, Any from BiddingKG.dl.template_extract.abstract_template import AbstractTemplate, table2list import os import json class CustomBudgetTemplate(AbstractTemplate): """ 招标信息提取模板(适配data.json第一个表格) 适配包含"标的名称、概算金额、最高限价"列的招标信息表格提取 """ def __init__(self): super().__init__( template_id=os.path.abspath(__file__), priority=3 ) def check_call_timing(self, preprocessed_data: Dict[str, Any]) -> bool: """检查是否符合模板调用条件""" if "表格列表" not in preprocessed_data: return False tables = preprocessed_data["表格列表"] if len(tables) < 1: return False try: datas = tables[0] # 验证表头列数(目标表格为5列) if len(datas[0]) != 5: print("表头数量异常;", len(datas[0])) return False # 表头内容正则匹配 header_patterns = [ '序号', # 第1列:序号 '标的名称', # 第2列:标的名称 '(概算|预算)金额([万亿美欧日]?元)', # 第3列:概算金额 '最高限价([万亿美欧日]?元)', # 第4列:最高限价 '服务期/工期|工期/服务期|工期/交货期|交货期/工期|服务期|工期|交货期' # 第5列:工期 ] # 逐列验证表头 for i, pattern in enumerate(header_patterns): if not re.fullmatch(pattern, datas[0][i]): print('表头未验证: ', pattern, datas[0][i]) return False # 确保表格有数据行 if len(datas) < 2: return False self.header = datas[0] self.data = datas[1:] return True except Exception as e: print(f"表格验证错误: {e}") return False def extract(self, preprocessed_data: Dict[str, Any]) -> Dict[str, Any]: """提取表格中的招标信息、中标信息、候选人信息""" extract_result = { "招标信息": [], "中标信息": [], "候选人信息": [] } for row in self.data: # 跳过列数异常的行 if len(row) != 5: continue # 解析每行数据 seq, subject_name, budget, limited_price, _ = row # 补充报价单位(如果表头有单位而内容没有) if re.search('[万亿美欧日]?元', self.header[2]) and not re.search('[万亿美欧日]?元', budget): budget += re.search('[万亿美欧日]?元', self.header[2]).group(0) if re.search('[万亿美欧日]?元', self.header[3]) and not re.search('[万亿美欧日]?元', limited_price): limited_price += re.search('[万亿美欧日]?元', self.header[3]).group(0) # 提取招标信息(包含预算,符合必填条件) tender_info = { "标的": subject_name, "预算": budget, "限价": limited_price } # 过滤空值字段 tender_info = {k: v for k, v in tender_info.items() if v} extract_result["招标信息"].append(tender_info) return extract_result # 使用示例 if __name__ == "__main__": # 读取数据文件 with open("data.json", "r", encoding="utf8") as f: preprocessed_data = json.load(f) # 初始化模板并提取信息 template = CustomBudgetTemplate() if template.check_call_timing(preprocessed_data): result = template.extract(preprocessed_data) print("提取结果:", json.dumps(result, ensure_ascii=False, indent=2)) else: print("当前数据不满足模板调用条件")