template33.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. # coding:utf8
  2. import re
  3. from typing import Dict, Any
  4. from BiddingKG.dl.template_extract.abstract_template import AbstractTemplate
  5. import os
  6. import json
  7. class BidWinnerTemplate(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. # 检查表头列数是否足够
  31. if len(datas[0]) < 6:
  32. print(f"表头数量异常;实际{len(datas[0])}列,要求最少6列")
  33. return False
  34. # 定义需要匹配的表头正则(泛化表达)
  35. required_headers = [
  36. '序号', # 序号(精确匹配)
  37. '标的(名称)?', # 标的名称(泛化匹配)
  38. '标[包段](名称)?', # 标包名称(泛化匹配)
  39. '(中标|成交)人?候选人排序|推荐排序', # 中标候选人排序(精确匹配)
  40. '(中标|成交)候选人名称', # 中标候选人名称(精确匹配)
  41. '((投标|响应|最终)(\w{,8})?报价|投标金额)(([万亿美欧日]?元(/\w)*))?((不?含税))?' # 投标报价(泛化匹配)
  42. ]
  43. # 记录每个表头的匹配列索引
  44. self.header_indices = {}
  45. matched_count = 0
  46. # 遍历表头列,检查是否包含所有必需项(顺序不固定)
  47. for col_idx, col_name in enumerate(header):
  48. for req_idx, pattern in enumerate(required_headers):
  49. if re.fullmatch(pattern, col_name):
  50. # 记录匹配到的列索引(使用需求名称作为key)
  51. req_key = {
  52. 0: "序号",
  53. 1: "标的名称",
  54. 2: "标包名称",
  55. 3: "中标候选人排序",
  56. 4: "中标候选人名称",
  57. 5: "投标报价"
  58. }[req_idx]
  59. if req_key not in self.header_indices:
  60. self.header_indices[req_key] = col_idx
  61. matched_count += 1
  62. break # 一个列只匹配一个需求
  63. # 必须匹配到所有必需表头
  64. if matched_count != len(required_headers):
  65. print(f"未匹配到所有必需表头,已匹配{matched_count}/{len(required_headers)}")
  66. return False
  67. # 确保表格有数据行
  68. if len(datas) < 2:
  69. print("表格没有数据行")
  70. return False
  71. self.header = header
  72. self.data = datas[1:]
  73. return True
  74. except Exception as e:
  75. print(f"表格验证错误: {e}")
  76. return False
  77. def extract(self, preprocessed_data: Dict[str, Any]) -> Dict[str, Any]:
  78. """提取表格中的中标信息"""
  79. extract_result = {"候选人信息": []}
  80. for row in self.data:
  81. # 跳过长度异常的行
  82. if len(row) != len(self.header):
  83. continue
  84. # 根据表头索引提取对应数据
  85. serial_number = row[self.header_indices["序号"]]
  86. subject = row[self.header_indices["标的名称"]]
  87. package = row[self.header_indices["标包名称"]]
  88. winner_rank = row[self.header_indices["中标候选人排序"]]
  89. winner_name = row[self.header_indices["中标候选人名称"]]
  90. bid_price = row[self.header_indices["投标报价"]]
  91. # 处理投标报价单位(从表头继承单位)
  92. price_header = self.header[self.header_indices["投标报价"]]
  93. if re.search('[万亿美欧日]?元', price_header) and not re.search('[万亿美欧日]?元', bid_price):
  94. bid_price += re.search('[万亿美欧日]?元', price_header).group(0)
  95. # 整理信息
  96. extract_result["候选人信息"].append({
  97. "标的": subject,
  98. "标包": package,
  99. "排名": winner_rank,
  100. "候选人": winner_name,
  101. "投标价": bid_price,
  102. })
  103. return extract_result
  104. # 使用示例
  105. if __name__ == "__main__":
  106. # 读取数据文件
  107. with open("data.json", "r", encoding="utf8") as f:
  108. preprocessed_data = json.load(f)
  109. # 初始化模板并提取信息
  110. template = BidWinnerTemplate()
  111. if template.check_call_timing(preprocessed_data):
  112. result = template.extract(preprocessed_data)
  113. print("提取结果:", json.dumps(result, ensure_ascii=False, indent=2))
  114. else:
  115. print("当前数据不满足模板调用条件")