deduplicator.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. """
  2. 去重工具模块
  3. """
  4. from typing import List, Dict, Any
  5. def deduplicate_records(
  6. records: List[Dict[str, Any]],
  7. keys: List[str] = None
  8. ) -> List[Dict[str, Any]]:
  9. """
  10. 根据指定 key 去重
  11. 默认 key: 客户姓名/公司 + 城市 + 主页/链接
  12. """
  13. if keys is None:
  14. keys = ["客户姓名/公司", "城市", "主页/链接"]
  15. seen = set()
  16. unique_records = []
  17. for record in records:
  18. key_values = []
  19. for key in keys:
  20. value = str(record.get(key, "")).strip().lower()
  21. key_values.append(value)
  22. signature = "|".join(key_values)
  23. if signature and signature not in seen:
  24. seen.add(signature)
  25. unique_records.append(record)
  26. elif not signature:
  27. # 空签名也保留,避免误删
  28. unique_records.append(record)
  29. return unique_records
  30. def merge_records(
  31. existing: List[Dict[str, Any]],
  32. new: List[Dict[str, Any]],
  33. keys: List[str] = None
  34. ) -> List[Dict[str, Any]]:
  35. """合并两组记录并去重"""
  36. combined = existing + new
  37. return deduplicate_records(combined, keys)