template6.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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 ProductInfoTemplate(AbstractTemplate):
  8. """
  9. 产品信息提取模板(适配data.json中的第二个表格结构)
  10. 从第二个表格提取产品相关信息
  11. """
  12. def __init__(self):
  13. super().__init__(
  14. template_id=os.path.abspath(__file__),
  15. priority=3
  16. )
  17. self.target_table = None # 第二个表格,存储产品信息
  18. def check_call_timing(self, preprocessed_data: Dict[str, Any]) -> bool:
  19. """检查是否符合模板调用条件"""
  20. if "表格列表" not in preprocessed_data:
  21. return False
  22. tables = preprocessed_data["表格列表"]
  23. if len(tables) < 1:
  24. print("表格数量不足,至少需要2个表格")
  25. return False
  26. try:
  27. self.target_table = tables[0] # 只处理第二个表格
  28. # 验证表格关键表头(按data.json第二个表格实际结构泛化匹配)
  29. header_patterns = [
  30. (0, 0, r'采购品目|品目'), # 第1行第1列
  31. (0, 2, r'名称|产品名称'), # 第1行第3列
  32. (1, 0, r'单位|计量单位'), # 第2行第1列
  33. (1, 2, r'数量'), # 第2行第3列
  34. (2, 0, r'单价'), # 第3行第1列
  35. (2, 2, r'总价|总金额'), # 第3行第3列
  36. ]
  37. # 验证表头
  38. for row, col, pattern in header_patterns:
  39. if row >= len(self.target_table) or col >= len(self.target_table[row]):
  40. return False
  41. header_text = self.target_table[row][col].strip()
  42. if not re.search(pattern, header_text, re.IGNORECASE):
  43. print(f"表头不匹配: {header_text} 不符合 {pattern}")
  44. return False
  45. return True
  46. except Exception as e:
  47. print(f"表格验证错误: {e}")
  48. return False
  49. def extract(self, preprocessed_data: Dict[str, Any]) -> Dict[str, Any]:
  50. """提取表格中的产品信息"""
  51. result = {"产品信息": []}
  52. # 提取产品信息
  53. product_info = self._extract_product_info()
  54. if product_info:
  55. result["产品信息"].append(product_info)
  56. return result
  57. def _get_value(self, table: list, row: int, col: int) -> str:
  58. """获取表格指定位置的值"""
  59. if row < len(table) and col < len(table[row]):
  60. return table[row][col].strip()
  61. return ""
  62. def _format_amount(self, value: str, header_row: int, header_col: int) -> str:
  63. """格式化金额,补充单位"""
  64. if not value:
  65. return ""
  66. # 检查值中是否已包含单位
  67. if re.search(r'[万亿美欧日]?元|¥|人民币', value):
  68. return value
  69. # 从表头获取单位补充
  70. header_text = self._get_value(self.target_table, header_row, header_col)
  71. if re.search(r'[万亿美欧日]?元|¥|人民币', header_text):
  72. unit = re.search(r'[万亿美欧日]?元|¥|人民币', header_text).group(0)
  73. return f"{value}{unit}"
  74. return value
  75. def _extract_product_info(self) -> Dict[str, Any]:
  76. """提取产品详细信息"""
  77. product = {
  78. "产品": self._get_value(self.target_table, 0, 3), # 产品名称
  79. "品目": self._get_value(self.target_table, 0, 1), # 采购品目
  80. "数量": self._get_value(self.target_table, 1, 3), # 数量
  81. "单位": self._get_value(self.target_table, 1, 1), # 计量单位
  82. "单价": self._format_amount(self._get_value(self.target_table, 2, 1), 2, 0), # 单价(补充单位)
  83. "总价": self._format_amount(self._get_value(self.target_table, 2, 3), 2, 2), # 总价(补充单位)
  84. # 品牌和规格在当前表格中不存在,不提取
  85. }
  86. # 过滤空值字段
  87. return {k: v for k, v in product.items() if v}
  88. # 使用示例
  89. if __name__ == "__main__":
  90. with open("data.json", "r", encoding="utf8") as f:
  91. preprocessed_data = json.load(f)
  92. template = ProductInfoTemplate()
  93. if template.check_call_timing(preprocessed_data):
  94. result = template.extract(preprocessed_data)
  95. print("提取结果:", json.dumps(result, ensure_ascii=False, indent=2))
  96. else:
  97. print("当前数据不满足模板调用条件")