feat: 楼宇轮廓 CSV 按内容自动识别编码

This commit is contained in:
nixevol
2026-09-17 09:38:22 +08:00
parent 859ac1df73
commit e96eed0f6c
5 changed files with 73 additions and 16 deletions
+42 -4
View File
@@ -51,6 +51,44 @@ class AuthenticationError(QueryError):
pass
ENCODING_CANDIDATES = ("gbk", "utf-8-sig")
def detect_encoding(path, preferred=None, required=(ID_COLUMN, WKT_COLUMN)):
"""按文件内容自动判定编码,返回能读出必需表头的编码。
GBK 对 UTF-8 字节流很宽容,会“成功”解出乱码,所以不能只靠解码是否报错:
样本含非 ASCII 且能通过严格 UTF-8 解码就判为 UTF-8,否则判为 GBK;
纯 ASCII 样本两种编码等价,沿用首选编码。判定结果读不出表头时再试其余候选。
"""
path = Path(path)
with path.open("rb") as raw:
head = raw.read(1024 * 1024)
# 只按最后一个换行截断,避免样本末尾切断多字节字符造成误判。
sample = head[:head.rfind(b"\n") + 1] or head
order = []
if head.startswith(b"\xef\xbb\xbf"):
order.append("utf-8-sig")
elif not sample.isascii():
try:
sample.decode("utf-8")
order.append("utf-8-sig")
except UnicodeDecodeError:
order.append("gbk")
if preferred and preferred not in order:
order.append(preferred)
order.extend(candidate for candidate in ENCODING_CANDIDATES if candidate not in order)
for encoding in order:
try:
text = sample.decode(encoding)
except (UnicodeDecodeError, LookupError):
continue
fieldnames = next(csv.reader(text.splitlines()[:1]), [])
if set(required) <= set(fieldnames):
return encoding
raise ValueError(f"无法按 {'/'.join(order)} 读取表头,输入 CSV 必须包含列:{', '.join(required)}")
def interior_point(text):
"""返回一定位于轮廓内部的 (经度, 纬度) 字符串。
@@ -281,11 +319,11 @@ async def async_main(*, handle_signals=True, should_stop=None, progress=None):
finally:
await loop.run_in_executor(executor, writer.close)
with input_path.open("r", encoding=INPUT_ENCODING, newline="") as source:
encoding = detect_encoding(input_path, INPUT_ENCODING)
if encoding != INPUT_ENCODING:
print(f"输入文件按 {encoding} 读取(首选 {INPUT_ENCODING} 无法识别表头)", flush=True)
with input_path.open("r", encoding=encoding, newline="") as source:
reader = csv.DictReader(source)
required = {ID_COLUMN, WKT_COLUMN}
if not required.issubset(reader.fieldnames or []):
raise ValueError(f"输入 CSV 必须包含列:{', '.join(sorted(required))}")
# 输入行号从 1 计(不含表头),便于按行号断点重跑和区分重复 building_id。
selected = islice(enumerate(reader, 1), START_ROW - 1, None if LIMIT is None else START_ROW - 1 + LIMIT)
old_signal_handler = None