fix: 回写清洗后的楼宇结果 CSV
This commit is contained in:
+10
-1
@@ -30,7 +30,8 @@ def build_gpkg(data_csv, polygon_csv, output_path):
|
||||
except Exception: continue
|
||||
if not geometry.is_empty and geometry.is_valid:
|
||||
polygons.setdefault(str(row["building_id"]), geometry)
|
||||
with data_csv.open(encoding=_encoding(data_csv), newline="") as f:
|
||||
data_encoding = _encoding(data_csv)
|
||||
with data_csv.open(encoding=data_encoding, newline="") as f:
|
||||
reader = csv.DictReader(f)
|
||||
fields = [x for x in (reader.fieldnames or []) if x not in DROP_COLUMNS]
|
||||
if "building_id" not in fields: raise ValueError("楼宇结果 CSV 缺少 building_id 字段")
|
||||
@@ -40,6 +41,14 @@ def build_gpkg(data_csv, polygon_csv, output_path):
|
||||
geometry=polygons.get(str(row.get("building_id", "")).strip())
|
||||
if not geometry or (row.get("查询状态", "").strip() and row.get("查询状态", "").strip() not in {"成功", "命中"}): continue
|
||||
clean={x:row.get(x, "") for x in fields if x != "WKT"}; clean["WKT"]=geometry.wkt; rows.append((clean,geometry))
|
||||
# 先原子回写清洗后的 CSV,避免中途失败破坏原文件。
|
||||
temporary_csv = data_csv.with_name(f".{data_csv.name}.tmp")
|
||||
with temporary_csv.open("w", encoding=data_encoding, newline="") as f:
|
||||
writer = csv.DictWriter(f, fieldnames=fields)
|
||||
writer.writeheader()
|
||||
writer.writerows(clean for clean, _ in rows)
|
||||
temporary_csv.replace(data_csv)
|
||||
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if output_path.exists(): output_path.unlink()
|
||||
conn=sqlite3.connect(output_path)
|
||||
|
||||
@@ -25,6 +25,10 @@ class NrDataTest(unittest.TestCase):
|
||||
writer.writerow(["2", "A", "失败", "超时", ""])
|
||||
result = build_gpkg(data, polygon, output)
|
||||
self.assertEqual(result["feature_count"], 1)
|
||||
with data.open(encoding="gbk", newline="") as stream:
|
||||
cleaned = csv.DictReader(stream)
|
||||
self.assertEqual(cleaned.fieldnames, ["building_id", "building_name", "WKT"])
|
||||
self.assertEqual(len(list(cleaned)), 1)
|
||||
conn = sqlite3.connect(output)
|
||||
try:
|
||||
columns = [row[1] for row in conn.execute('pragma table_info("NRBuildingsData")')]
|
||||
|
||||
Reference in New Issue
Block a user