table_comparator.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. import re
  2. from typing import Dict, List, Tuple, Optional
  3. try:
  4. from .data_type_detector import DataTypeDetector
  5. from .similarity_calculator import SimilarityCalculator
  6. from .text_processor import TextProcessor
  7. except ImportError:
  8. from data_type_detector import DataTypeDetector
  9. from similarity_calculator import SimilarityCalculator
  10. from text_processor import TextProcessor
  11. class TableComparator:
  12. """表格数据比较"""
  13. def __init__(self):
  14. self.detector = DataTypeDetector()
  15. self.calculator = SimilarityCalculator()
  16. self.text_processor = TextProcessor()
  17. self.header_similarity_threshold = 90
  18. self.content_similarity_threshold = 95
  19. self.max_paragraph_window = 6
  20. def find_matching_tables(self, tables1: List[List[List[str]]],
  21. tables2: List[List[List[str]]]) -> List[Tuple[int, int, float]]:
  22. """
  23. 智能匹配两个文件中的表格
  24. Returns:
  25. List[Tuple[int, int, float]]: (table1_index, table2_index, similarity_score)
  26. """
  27. matches = []
  28. for i, table1 in enumerate(tables1):
  29. if not table1:
  30. continue
  31. best_match = None
  32. best_score = 0
  33. for j, table2 in enumerate(tables2):
  34. if not table2:
  35. continue
  36. # 计算表格相似度
  37. score = self._calculate_table_similarity(table1, table2)
  38. if score > best_score:
  39. best_score = score
  40. best_match = j
  41. if best_match is not None and best_score > 50: # 至少50%相似度
  42. matches.append((i, best_match, best_score))
  43. print(f" 📊 表格匹配: 文件1表格{i+1} ↔ 文件2表格{best_match+1} (相似度: {best_score:.1f}%)")
  44. return matches
  45. def _get_max_columns(self, table: List[List[str]]) -> int:
  46. """获取表格的最大列数"""
  47. if not table:
  48. return 0
  49. return max(len(row) for row in table)
  50. def _calculate_table_similarity(self, table1: List[List[str]],
  51. table2: List[List[str]]) -> float:
  52. """计算两个表格的相似度"""
  53. if not table1 or not table2:
  54. return 0.0
  55. # 1. 行数相似度 (权重: 15%)
  56. row_count1 = len(table1)
  57. row_count2 = len(table2)
  58. row_similarity = 100 * (1 - abs(row_count1 - row_count2) / max(row_count1, row_count2))
  59. # 2. 列数相似度 (权重: 15%) - ✅ 使用最大列数
  60. col_count1 = self._get_max_columns(table1)
  61. col_count2 = self._get_max_columns(table2)
  62. max_cols = max(col_count1, col_count2)
  63. min_cols = min(col_count1, col_count2)
  64. if max_cols == 0:
  65. col_similarity = 0
  66. else:
  67. # 如果列数差异在合理范围内(比如差1-2列),给予较高分数
  68. col_diff = abs(col_count1 - col_count2)
  69. if col_diff == 0:
  70. col_similarity = 100
  71. elif col_diff <= 2:
  72. # 差1-2列,给予80-95分
  73. col_similarity = 100 - (col_diff * 10)
  74. else:
  75. # 差异较大时,使用比例计算
  76. col_similarity = 100 * (min_cols / max_cols)
  77. print(f" 行数对比: {row_count1} vs {row_count2}, 相似度: {row_similarity:.1f}%")
  78. print(f" 列数对比: {col_count1} vs {col_count2}, 相似度: {col_similarity:.1f}%")
  79. # 3. 表头相似度 (权重: 50%) - ✅ 先检测表头位置
  80. header_row_idx1 = self.detect_table_header_row(table1)
  81. header_row_idx2 = self.detect_table_header_row(table2)
  82. print(f" 表头位置: 文件1第{header_row_idx1+1}行, 文件2第{header_row_idx2+1}行")
  83. header_similarity = 0
  84. if header_row_idx1 < len(table1) and header_row_idx2 < len(table2):
  85. header1 = table1[header_row_idx1]
  86. header2 = table2[header_row_idx2]
  87. if header1 and header2:
  88. # ✅ 智能表头匹配
  89. header_similarity = self._calculate_header_similarity_smart(header1, header2)
  90. print(f" 表头相似度: {header_similarity:.1f}%")
  91. # 4. 内容特征相似度 (权重: 20%)
  92. content_similarity = self._calculate_content_features_similarity(table1, table2)
  93. print(f" 内容特征相似度: {content_similarity:.1f}%")
  94. # ✅ 调整权重分配
  95. total_similarity = (
  96. row_similarity * 0.15 + # 行数 15%
  97. col_similarity * 0.15 + # 列数 15%
  98. header_similarity * 0.50 + # 表头 50% (最重要)
  99. content_similarity * 0.20 # 内容 20%
  100. )
  101. return total_similarity
  102. def _calculate_header_similarity_smart(self, header1: List[str],
  103. header2: List[str]) -> float:
  104. """
  105. 智能计算表头相似度
  106. 处理以下情况:
  107. 1. 列数不同但表头内容相似
  108. 2. PaddleOCR可能将多行表头合并
  109. 3. 表头顺序可能不同
  110. """
  111. if not header1 or not header2:
  112. return 0.0
  113. # 标准化表头
  114. norm_headers1 = [self.normalize_header_text(h) for h in header1]
  115. norm_headers2 = [self.normalize_header_text(h) for h in header2]
  116. # 方法1: 精确匹配 (最高优先级)
  117. common_headers = set(norm_headers1) & set(norm_headers2)
  118. max_len = max(len(norm_headers1), len(norm_headers2))
  119. if max_len == 0:
  120. return 0.0
  121. exact_match_ratio = len(common_headers) / max_len
  122. # 方法2: 模糊匹配 (针对列数不同的情况)
  123. fuzzy_matches = 0
  124. # 使用较短的表头作为基准
  125. if len(norm_headers1) <= len(norm_headers2):
  126. base_headers = norm_headers1
  127. compare_headers = norm_headers2
  128. else:
  129. base_headers = norm_headers2
  130. compare_headers = norm_headers1
  131. for base_h in base_headers:
  132. best_similarity = 0
  133. for comp_h in compare_headers:
  134. similarity = self.calculator.calculate_text_similarity(base_h, comp_h)
  135. if similarity > best_similarity:
  136. best_similarity = similarity
  137. if best_similarity == 100:
  138. break
  139. # 如果相似度超过70%,认为是匹配的
  140. if best_similarity > 70:
  141. fuzzy_matches += 1
  142. fuzzy_match_ratio = fuzzy_matches / max_len if max_len > 0 else 0
  143. # 方法3: 关键字匹配 (识别常见表头)
  144. key_headers = {
  145. 'date': ['日期', 'date', '时间', 'time'],
  146. 'type': ['类型', 'type', '业务', 'business'],
  147. 'number': ['号', 'no', '编号', 'id', '票据', 'bill'],
  148. 'description': ['摘要', 'description', '说明', 'remark'],
  149. 'amount': ['金额', 'amount', '借方', 'debit', '贷方', 'credit'],
  150. 'balance': ['余额', 'balance'],
  151. 'counterparty': ['对手', 'counterparty', '账户', 'account', '户名', 'name']
  152. }
  153. def categorize_header(h: str) -> set:
  154. categories = set()
  155. h_lower = h.lower()
  156. for category, keywords in key_headers.items():
  157. for keyword in keywords:
  158. if keyword in h_lower:
  159. categories.add(category)
  160. return categories
  161. categories1 = set()
  162. for h in norm_headers1:
  163. categories1.update(categorize_header(h))
  164. categories2 = set()
  165. for h in norm_headers2:
  166. categories2.update(categorize_header(h))
  167. common_categories = categories1 & categories2
  168. all_categories = categories1 | categories2
  169. category_match_ratio = len(common_categories) / len(all_categories) if all_categories else 0
  170. # ✅ 综合三种方法,加权计算
  171. final_similarity = (
  172. exact_match_ratio * 0.4 + # 精确匹配 40%
  173. fuzzy_match_ratio * 0.4 + # 模糊匹配 40%
  174. category_match_ratio * 0.2 # 语义匹配 20%
  175. ) * 100
  176. print(f" 精确匹配: {exact_match_ratio:.1%}, 模糊匹配: {fuzzy_match_ratio:.1%}, 语义匹配: {category_match_ratio:.1%}")
  177. return final_similarity
  178. def _calculate_content_features_similarity(self, table1: List[List[str]],
  179. table2: List[List[str]]) -> float:
  180. """计算表格内容特征相似度"""
  181. # 统计数字、日期等特征
  182. features1 = self._extract_table_features(table1)
  183. features2 = self._extract_table_features(table2)
  184. # 比较特征
  185. similarity_scores = []
  186. for key in ['numeric_ratio', 'date_ratio', 'empty_ratio']:
  187. if key in features1 and key in features2:
  188. diff = abs(features1[key] - features2[key])
  189. similarity_scores.append(100 * (1 - diff))
  190. return sum(similarity_scores) / len(similarity_scores) if similarity_scores else 0
  191. def _extract_table_features(self, table: List[List[str]]) -> Dict:
  192. """提取表格特征"""
  193. total_cells = 0
  194. numeric_cells = 0
  195. date_cells = 0
  196. empty_cells = 0
  197. for row in table:
  198. for cell in row:
  199. total_cells += 1
  200. if not cell or cell.strip() == '':
  201. empty_cells += 1
  202. continue
  203. if self.detector.is_numeric(cell):
  204. numeric_cells += 1
  205. if self.detector.extract_datetime(cell):
  206. date_cells += 1
  207. return {
  208. 'numeric_ratio': numeric_cells / total_cells if total_cells > 0 else 0,
  209. 'date_ratio': date_cells / total_cells if total_cells > 0 else 0,
  210. 'empty_ratio': empty_cells / total_cells if total_cells > 0 else 0,
  211. 'total_cells': total_cells
  212. }
  213. def normalize_header_text(self, text: str) -> str:
  214. """标准化表头文本"""
  215. # 移除括号内容
  216. text = re.sub(r'[((].*?[))]', '', text)
  217. # 移除空格
  218. text = re.sub(r'\s+', '', text)
  219. # 只保留字母、数字和中文
  220. text = re.sub(r'[^\w\u4e00-\u9fff]', '', text)
  221. return text.lower().strip()
  222. def detect_table_header_row(self, table: List[List[str]]) -> int:
  223. """
  224. 智能检测表格的表头行索引
  225. 检测策略:
  226. 1. 查找包含表头关键字最多的行
  227. 2. 确认下一行是数据行
  228. 3. 避免将合并单元格的元数据行误判为表头
  229. """
  230. if not table:
  231. return 0
  232. header_keywords = [
  233. '日期', 'date', '时间', 'time',
  234. '类型', 'type', '业务', 'business',
  235. '号', 'no', '编号', 'id', '票据', 'bill',
  236. '摘要', 'description', '说明', 'remark',
  237. '金额', 'amount', '借方', 'debit', '贷方', 'credit',
  238. '余额', 'balance',
  239. '对手', 'counterparty', '账户', 'account', '户名', 'name'
  240. ]
  241. best_header_row = 0
  242. best_score = 0
  243. for row_idx, row in enumerate(table[:5]): # 只检查前5行
  244. if not row:
  245. continue
  246. # 计算关键字匹配分数
  247. keyword_count = 0
  248. non_empty_cells = 0
  249. for cell in row:
  250. cell_text = str(cell).strip()
  251. if cell_text:
  252. non_empty_cells += 1
  253. cell_lower = cell_text.lower()
  254. for keyword in header_keywords:
  255. if keyword in cell_lower:
  256. keyword_count += 1
  257. break
  258. # 避免空行或几乎空的行
  259. if non_empty_cells < 3:
  260. continue
  261. # 计算得分:关键字比例 + 列数奖励
  262. keyword_ratio = keyword_count / non_empty_cells if non_empty_cells > 0 else 0
  263. column_bonus = min(non_empty_cells / 5, 1.0) # 列数越多,奖励越高
  264. score = keyword_ratio * 0.7 + column_bonus * 0.3
  265. # 如果下一行是数据行,加分
  266. if row_idx + 1 < len(table):
  267. next_row = table[row_idx + 1]
  268. if self._is_data_row(next_row):
  269. score += 0.2
  270. if score > best_score:
  271. best_score = score
  272. best_header_row = row_idx
  273. # 如果最佳得分太低,返回0(第一行)
  274. if best_score < 0.3:
  275. print(f" ⚠️ 未检测到明确表头,默认使用第1行 (得分: {best_score:.2f})")
  276. return 0
  277. print(f" 📍 检测到表头在第 {best_header_row + 1} 行 (得分: {best_score:.2f})")
  278. return best_header_row
  279. def _is_data_row(self, row: List[str]) -> bool:
  280. """判断是否为数据行"""
  281. if not row:
  282. return False
  283. data_pattern_count = 0
  284. non_empty_count = 0
  285. for cell in row:
  286. cell_text = str(cell).strip()
  287. if not cell_text:
  288. continue
  289. non_empty_count += 1
  290. # 包含数字
  291. if re.search(r'\d', cell_text):
  292. data_pattern_count += 1
  293. # 包含日期格式
  294. if re.search(r'\d{4}[-/年]\d{1,2}[-/月]\d{1,2}', cell_text):
  295. data_pattern_count += 1
  296. # 包含金额格式
  297. if re.search(r'-?\d+[,,]?\d*\.?\d+', cell_text):
  298. data_pattern_count += 1
  299. if non_empty_count == 0:
  300. return False
  301. # 至少30%的单元格包含数据特征
  302. return data_pattern_count / non_empty_count >= 0.3
  303. def compare_table_headers(self, headers1: List[str], headers2: List[str]) -> Dict:
  304. """比较表格表头"""
  305. result = {
  306. 'match': True,
  307. 'differences': [],
  308. 'column_mapping': {},
  309. 'similarity_scores': []
  310. }
  311. if len(headers1) != len(headers2):
  312. result['match'] = False
  313. result['differences'].append({
  314. 'type': 'table_header_critical',
  315. 'description': f'表头列数不一致: {len(headers1)} vs {len(headers2)}',
  316. 'severity': 'critical'
  317. })
  318. return result
  319. for i, (h1, h2) in enumerate(zip(headers1, headers2)):
  320. norm_h1 = self.normalize_header_text(h1)
  321. norm_h2 = self.normalize_header_text(h2)
  322. similarity = self.calculator.calculate_text_similarity(norm_h1, norm_h2)
  323. result['similarity_scores'].append({
  324. 'column_index': i,
  325. 'header1': h1,
  326. 'header2': h2,
  327. 'similarity': similarity
  328. })
  329. if similarity < self.header_similarity_threshold:
  330. result['match'] = False
  331. result['differences'].append({
  332. 'type': 'table_header_mismatch',
  333. 'column_index': i,
  334. 'header1': h1,
  335. 'header2': h2,
  336. 'similarity': similarity,
  337. 'description': f'第{i+1}列表头不匹配: "{h1}" vs "{h2}" (相似度: {similarity:.1f}%)',
  338. 'severity': 'medium' if similarity < 50 else 'high'
  339. })
  340. else:
  341. result['column_mapping'][i] = i
  342. return result
  343. def compare_cell_value(self, value1: str, value2: str, column_type: str,
  344. column_name: str = '') -> Dict:
  345. """比较单元格值"""
  346. result = {
  347. 'match': True,
  348. 'difference': None
  349. }
  350. v1 = self.text_processor.normalize_text(value1)
  351. v2 = self.text_processor.normalize_text(value2)
  352. if v1 == v2:
  353. return result
  354. if column_type == 'text_number':
  355. norm_v1 = self.detector.normalize_text_number(v1)
  356. norm_v2 = self.detector.normalize_text_number(v2)
  357. if norm_v1 == norm_v2:
  358. result['match'] = False
  359. result['difference'] = {
  360. 'type': 'table_text',
  361. 'value1': value1,
  362. 'value2': value2,
  363. 'description': f'文本型数字格式差异: "{value1}" vs "{value2}" (内容相同,空格不同)',
  364. 'severity': 'low'
  365. }
  366. else:
  367. result['match'] = False
  368. result['difference'] = {
  369. 'type': 'table_text',
  370. 'value1': value1,
  371. 'value2': value2,
  372. 'description': f'文本型数字不一致: {value1} vs {value2}',
  373. 'severity': 'high'
  374. }
  375. return result
  376. if column_type == 'numeric':
  377. if self.detector.is_numeric(v1) and self.detector.is_numeric(v2):
  378. num1 = self.detector.parse_number(v1)
  379. num2 = self.detector.parse_number(v2)
  380. if abs(num1 - num2) > 0.01:
  381. result['match'] = False
  382. result['difference'] = {
  383. 'type': 'table_amount',
  384. 'value1': value1,
  385. 'value2': value2,
  386. 'diff_amount': abs(num1 - num2),
  387. 'description': f'金额不一致: {value1} vs {value2}'
  388. }
  389. else:
  390. result['match'] = False
  391. result['difference'] = {
  392. 'type': 'table_text',
  393. 'value1': value1,
  394. 'value2': value2,
  395. 'description': f'长数字字符串不一致: {value1} vs {value2}'
  396. }
  397. elif column_type == 'datetime':
  398. datetime1 = self.detector.extract_datetime(v1)
  399. datetime2 = self.detector.extract_datetime(v2)
  400. if datetime1 != datetime2:
  401. result['match'] = False
  402. result['difference'] = {
  403. 'type': 'table_datetime',
  404. 'value1': value1,
  405. 'value2': value2,
  406. 'description': f'日期时间不一致: {value1} vs {value2}'
  407. }
  408. else:
  409. similarity = self.calculator.calculate_text_similarity(v1, v2)
  410. if similarity < self.content_similarity_threshold:
  411. result['match'] = False
  412. result['difference'] = {
  413. 'type': 'table_text',
  414. 'value1': value1,
  415. 'value2': value2,
  416. 'similarity': similarity,
  417. 'description': f'文本不一致: {value1} vs {value2} (相似度: {similarity:.1f}%)'
  418. }
  419. return result
  420. def compare_tables(self, table1: List[List[str]], table2: List[List[str]]) -> List[Dict]:
  421. """标准表格比较"""
  422. differences = []
  423. max_rows = max(len(table1), len(table2))
  424. for i in range(max_rows):
  425. row1 = table1[i] if i < len(table1) else []
  426. row2 = table2[i] if i < len(table2) else []
  427. max_cols = max(len(row1), len(row2))
  428. for j in range(max_cols):
  429. cell1 = row1[j] if j < len(row1) else ""
  430. cell2 = row2[j] if j < len(row2) else ""
  431. if "[图片内容-忽略]" in cell1 or "[图片内容-忽略]" in cell2:
  432. continue
  433. if cell1 != cell2:
  434. if self.detector.is_numeric(cell1) and self.detector.is_numeric(cell2):
  435. num1 = self.detector.parse_number(cell1)
  436. num2 = self.detector.parse_number(cell2)
  437. if abs(num1 - num2) > 0.001:
  438. differences.append({
  439. 'type': 'table_amount',
  440. 'position': f'行{i+1}列{j+1}',
  441. 'file1_value': cell1,
  442. 'file2_value': cell2,
  443. 'description': f'金额不一致: {cell1} vs {cell2}',
  444. 'row_index': i,
  445. 'col_index': j
  446. })
  447. else:
  448. differences.append({
  449. 'type': 'table_text',
  450. 'position': f'行{i+1}列{j+1}',
  451. 'file1_value': cell1,
  452. 'file2_value': cell2,
  453. 'description': f'文本不一致: {cell1} vs {cell2}',
  454. 'row_index': i,
  455. 'col_index': j
  456. })
  457. return differences
  458. def compare_table_flow_list(self, table1: List[List[str]], table2: List[List[str]]) -> List[Dict]:
  459. """流水列表表格比较算法"""
  460. differences = []
  461. if not table1 or not table2:
  462. return [{
  463. 'type': 'table_empty',
  464. 'description': '表格为空',
  465. 'severity': 'critical'
  466. }]
  467. print(f"\n📋 开始流水表格对比...")
  468. # 检测表头位置
  469. header_row_idx1 = self.detect_table_header_row(table1)
  470. header_row_idx2 = self.detect_table_header_row(table2)
  471. if header_row_idx1 != header_row_idx2:
  472. differences.append({
  473. 'type': 'table_header_position',
  474. 'position': '表头位置',
  475. 'file1_value': f'第{header_row_idx1 + 1}行',
  476. 'file2_value': f'第{header_row_idx2 + 1}行',
  477. 'description': f'表头位置不一致: 文件1在第{header_row_idx1 + 1}行,文件2在第{header_row_idx2 + 1}行',
  478. 'severity': 'high'
  479. })
  480. # 比对表头前的内容
  481. if header_row_idx1 > 0 or header_row_idx2 > 0:
  482. print(f"\n📝 对比表头前的内容...")
  483. pre_header_table1 = table1[:header_row_idx1] if header_row_idx1 > 0 else []
  484. pre_header_table2 = table2[:header_row_idx2] if header_row_idx2 > 0 else []
  485. if pre_header_table1 or pre_header_table2:
  486. pre_header_diffs = self.compare_tables(pre_header_table1, pre_header_table2)
  487. for diff in pre_header_diffs:
  488. diff['type'] = 'table_pre_header'
  489. diff['position'] = f"表头前{diff['position']}"
  490. diff['severity'] = 'medium'
  491. differences.extend(pre_header_diffs)
  492. # 比较表头
  493. headers1 = table1[header_row_idx1]
  494. headers2 = table2[header_row_idx2]
  495. print(f"\n📋 对比表头...")
  496. header_result = self.compare_table_headers(headers1, headers2)
  497. if not header_result['match']:
  498. print(f"\n⚠️ 表头文字存在差异")
  499. for diff in header_result['differences']:
  500. differences.append({
  501. 'type': diff.get('type', 'table_header_mismatch'),
  502. 'position': '表头',
  503. 'file1_value': diff.get('header1', ''),
  504. 'file2_value': diff.get('header2', ''),
  505. 'description': diff['description'],
  506. 'severity': diff.get('severity', 'high'),
  507. })
  508. if diff.get('severity') == 'critical':
  509. return differences
  510. # 检测列类型并比较数据行
  511. column_types1 = self._detect_column_types(table1, header_row_idx1, headers1)
  512. column_types2 = self._detect_column_types(table2, header_row_idx2, headers2)
  513. # 处理列类型不匹配
  514. mismatched_columns = self._check_column_type_mismatch(
  515. column_types1, column_types2, headers1, headers2, differences
  516. )
  517. # 合并列类型
  518. column_types = self._merge_column_types(column_types1, column_types2, mismatched_columns)
  519. # 逐行比较数据
  520. data_diffs = self._compare_data_rows(
  521. table1, table2, header_row_idx1, header_row_idx2,
  522. headers1, column_types, mismatched_columns, header_result['match']
  523. )
  524. differences.extend(data_diffs)
  525. print(f"\n✅ 流水表格对比完成,发现 {len(differences)} 个差异")
  526. return differences
  527. def _detect_column_types(self, table: List[List[str]], header_row_idx: int,
  528. headers: List[str]) -> List[str]:
  529. """检测列类型"""
  530. column_types = []
  531. for col_idx in range(len(headers)):
  532. col_values = [
  533. row[col_idx]
  534. for row in table[header_row_idx + 1:]
  535. if col_idx < len(row)
  536. ]
  537. col_type = self.detector.detect_column_type(col_values)
  538. column_types.append(col_type)
  539. return column_types
  540. def _check_column_type_mismatch(self, column_types1: List[str], column_types2: List[str],
  541. headers1: List[str], headers2: List[str],
  542. differences: List[Dict]) -> List[int]:
  543. """检查列类型不匹配"""
  544. mismatched_columns = []
  545. for col_idx in range(min(len(column_types1), len(column_types2))):
  546. if column_types1[col_idx] != column_types2[col_idx]:
  547. mismatched_columns.append(col_idx)
  548. differences.append({
  549. 'type': 'table_column_type_mismatch',
  550. 'position': f'第{col_idx + 1}列',
  551. 'file1_value': f'{headers1[col_idx]} ({column_types1[col_idx]})',
  552. 'file2_value': f'{headers2[col_idx]} ({column_types2[col_idx]})',
  553. 'description': f'列类型不一致: {column_types1[col_idx]} vs {column_types2[col_idx]}',
  554. 'severity': 'high',
  555. 'column_index': col_idx
  556. })
  557. total_columns = min(len(column_types1), len(column_types2))
  558. mismatch_ratio = len(mismatched_columns) / total_columns if total_columns > 0 else 0
  559. if mismatch_ratio > 0.5:
  560. differences.append({
  561. 'type': 'table_header_critical',
  562. 'position': '表格列类型',
  563. 'file1_value': f'{len(mismatched_columns)}列类型不一致',
  564. 'file2_value': f'共{total_columns}列',
  565. 'description': f'列类型差异过大: {len(mismatched_columns)}/{total_columns}列不匹配 ({mismatch_ratio:.1%})',
  566. 'severity': 'critical'
  567. })
  568. return mismatched_columns
  569. def _merge_column_types(self, column_types1: List[str], column_types2: List[str],
  570. mismatched_columns: List[int]) -> List[str]:
  571. """合并列类型"""
  572. column_types = []
  573. for col_idx in range(max(len(column_types1), len(column_types2))):
  574. if col_idx >= len(column_types1):
  575. column_types.append(column_types2[col_idx])
  576. elif col_idx >= len(column_types2):
  577. column_types.append(column_types1[col_idx])
  578. elif col_idx in mismatched_columns:
  579. type1 = column_types1[col_idx]
  580. type2 = column_types2[col_idx]
  581. if type1 == 'text' or type2 == 'text':
  582. column_types.append('text')
  583. elif type1 == 'text_number' or type2 == 'text_number':
  584. column_types.append('text_number')
  585. else:
  586. column_types.append(type1)
  587. else:
  588. column_types.append(column_types1[col_idx])
  589. return column_types
  590. def _compare_data_rows(self, table1: List[List[str]], table2: List[List[str]],
  591. header_row_idx1: int, header_row_idx2: int,
  592. headers1: List[str], column_types: List[str],
  593. mismatched_columns: List[int], header_match: bool) -> List[Dict]:
  594. """逐行比较数据"""
  595. differences = []
  596. data_rows1 = table1[header_row_idx1 + 1:]
  597. data_rows2 = table2[header_row_idx2 + 1:]
  598. max_rows = max(len(data_rows1), len(data_rows2))
  599. for row_idx in range(max_rows):
  600. row1 = data_rows1[row_idx] if row_idx < len(data_rows1) else []
  601. row2 = data_rows2[row_idx] if row_idx < len(data_rows2) else []
  602. actual_row_num = header_row_idx1 + row_idx + 2
  603. if not row1:
  604. differences.append({
  605. 'type': 'table_row_missing',
  606. 'position': f'第{actual_row_num}行',
  607. 'file1_value': '',
  608. 'file2_value': ', '.join(row2),
  609. 'description': f'文件1缺少第{actual_row_num}行',
  610. 'severity': 'high',
  611. 'row_index': actual_row_num
  612. })
  613. continue
  614. if not row2:
  615. differences.append({
  616. 'type': 'table_row_missing',
  617. 'position': f'第{actual_row_num}行',
  618. 'file1_value': ', '.join(row1),
  619. 'file2_value': '',
  620. 'description': f'文件2缺少第{actual_row_num}行',
  621. 'severity': 'high',
  622. 'row_index': actual_row_num
  623. })
  624. continue
  625. # 逐列比较
  626. max_cols = max(len(row1), len(row2))
  627. for col_idx in range(max_cols):
  628. cell1 = row1[col_idx] if col_idx < len(row1) else ''
  629. cell2 = row2[col_idx] if col_idx < len(row2) else ''
  630. if "[图片内容-忽略]" in cell1 or "[图片内容-忽略]" in cell2:
  631. continue
  632. column_type = column_types[col_idx] if col_idx < len(column_types) else 'text'
  633. column_name = headers1[col_idx] if col_idx < len(headers1) else f'列{col_idx + 1}'
  634. compare_result = self.compare_cell_value(cell1, cell2, column_type, column_name)
  635. if not compare_result['match']:
  636. diff_info = compare_result['difference']
  637. type_mismatch_note = ""
  638. if col_idx in mismatched_columns:
  639. type_mismatch_note = " [列类型冲突]"
  640. differences.append({
  641. 'type': diff_info['type'],
  642. 'position': f'第{actual_row_num}行第{col_idx + 1}列',
  643. 'file1_value': diff_info['value1'],
  644. 'file2_value': diff_info['value2'],
  645. 'description': diff_info['description'] + type_mismatch_note,
  646. 'severity': 'high' if col_idx in mismatched_columns else 'medium',
  647. 'row_index': actual_row_num,
  648. 'col_index': col_idx,
  649. 'column_name': column_name,
  650. 'column_type': column_type,
  651. 'column_type_mismatch': col_idx in mismatched_columns,
  652. })
  653. return differences