template7.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. # coding:utf8
  2. import re
  3. from typing import Dict, Any
  4. from BiddingKG.dl.template_extract.abstract_template import AbstractTemplate, table2list
  5. import os
  6. import json
  7. class BudgetTemplate(AbstractTemplate):
  8. """
  9. 招标信息提取模板(适配多列表格场景)
  10. 适配包含"标的名称、标包名称、标包金额、最高限价"列的招标信息表格提取
  11. """
  12. def __init__(self):
  13. super().__init__(
  14. template_id=os.path.abspath(__file__),
  15. priority=5
  16. )
  17. def check_call_timing(self, preprocessed_data: Dict[str, Any]) -> bool:
  18. """检查是否符合模板调用条件,验证表头包含标的名称、标包名称、标包金额、最高限价(顺序不固定)"""
  19. if "表格列表" not in preprocessed_data:
  20. return False
  21. tables = preprocessed_data["表格列表"]
  22. if len(tables) < 1:
  23. return False
  24. try:
  25. datas = tables[0]
  26. # 确保表格有表头行
  27. if len(datas) < 1:
  28. return False
  29. header = datas[0]
  30. if len(datas[0]) < 6:
  31. print(f"表头数量异常;实际{len(datas[0])}列,要求最少6列")
  32. return False
  33. # 定义需要匹配的表头正则(泛化表达)
  34. required_headers = [
  35. '序号', # 序号(精确匹配)
  36. '标的(名称)?', # 标的名称(精确匹配)
  37. '标[包段](名称)?', # 标包名称(精确匹配)
  38. '(最高|上限)(投标)?限价(([万亿美欧日]?元(/\w)*))?' # 最高限价(泛化匹配)
  39. ]
  40. # 记录每个表头的匹配列索引
  41. self.header_indices = {}
  42. matched_count = 0
  43. # 遍历表头列,检查是否包含所有必需项(顺序不固定)
  44. for col_idx, col_name in enumerate(header):
  45. for req_idx, pattern in enumerate(required_headers):
  46. if re.fullmatch(pattern, col_name):
  47. # 记录匹配到的列索引(使用需求名称作为key)
  48. req_key = {
  49. 0: "序号",
  50. 1: "标的名称",
  51. 2: "标包名称",
  52. 3: "最高限价"
  53. }[req_idx]
  54. if req_key not in self.header_indices:
  55. self.header_indices[req_key] = col_idx
  56. matched_count += 1
  57. break # 一个列只匹配一个需求
  58. # 必须匹配到所有5个必需表头
  59. if matched_count != len(required_headers):
  60. print(f"未匹配到所有必需表头,已匹配{matched_count}")
  61. return False
  62. # 确保表格有数据行
  63. if len(datas) < 2:
  64. return False
  65. self.header = header
  66. self.data = datas[1:]
  67. return True
  68. except Exception as e:
  69. print(f"表格验证错误: {e}")
  70. return False
  71. def extract(self, preprocessed_data: Dict[str, Any]) -> Dict[str, Any]:
  72. """提取表格中的招标信息"""
  73. extract_result = {"招标信息": []}
  74. for row in self.data:
  75. # 跳过长度异常的行
  76. if len(row) != len(self.header):
  77. continue
  78. # 根据表头索引提取对应数据
  79. subject = row[self.header_indices["标的名称"]]
  80. package = row[self.header_indices["标包名称"]]
  81. # budget = row[self.header_indices["标包金额"]]
  82. limited_price = row[self.header_indices["最高限价"]]
  83. # 处理最高限价单位
  84. limit_header = self.header[self.header_indices["最高限价"]]
  85. if re.search('[万亿美欧日]?元', limit_header) and not re.search('[万亿美欧日]?元', limited_price):
  86. limited_price += re.search('[万亿美欧日]?元', limit_header).group(0)
  87. # 整理信息
  88. extract_result["招标信息"].append({
  89. "标的": subject,
  90. "标包": package,
  91. "限价": limited_price,
  92. })
  93. return extract_result
  94. # 使用示例
  95. if __name__ == "__main__":
  96. # 读取数据文件
  97. with open("data.json", "r", encoding="utf8") as f:
  98. preprocessed_data = json.load(f)
  99. # 初始化模板并提取信息
  100. template = BudgetTemplate()
  101. if template.check_call_timing(preprocessed_data):
  102. result = template.extract(preprocessed_data)
  103. print("提取结果:", json.dumps(result, ensure_ascii=False, indent=2))
  104. else:
  105. print("当前数据不满足模板调用条件")