历史订单地址清洗 API:批量补齐省市区、adcode 与邮编

电商、快递、本地生活系统里都躺着一批「野生地址」:用户从聊天窗口粘过来的一整段文本,姓名、电话、省市区、门牌号全挤在一行,有的写简称,有的漏区县,有的还带「*#」分隔符。要做区域报表、运费模板、配送范围校验,第一步就得把它们拆开、对齐成标准行政区划。

address.parse 专门做这件事:输入一段中文文本,输出姓名、电话、省 / 市 / 区县三级规范名称与 6 位 adcode、详细地址、邮政编码。解析不出省级行政区时不收费,适合存量数据批量治理。

接口速览

一、哪些业务需要这一步

二、请求参数

2.1 请求头

2.2 业务参数

服务端先取 Query 里的 text,为空再取 JSON body 里的 text。

三、返回字段

3.1 顶层

3.2 data 字段

3.3 姓名与电话的清洗规则

3.4 直辖市口径

注意:data 不含 keyword 字段;写解析代码时不要照抄企业系列接口的取法。

四、调用示例

4.1 curl

# GET
curl -s -G "https://api.xujian.tech/openapi/address/parse" \
  --data-urlencode "text=张三,13020260925,重庆市铜梁区白龙大道龙腾盛世" \
  -H "X-API-Key: 你的APIKey"

# POST
curl -s -X POST "https://api.xujian.tech/openapi/address/parse" \
  -H "X-API-Key: 你的APIKey" \
  -H "Content-Type: application/json" \
  -d '{"text":"张三,13020260925,重庆市铜梁区白龙大道龙腾盛世"}'

4.2 Java(Hutool)

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

public class AddressParseClient {

    private static final String API_URL = "https://api.xujian.tech/openapi/address/parse";

    /**
     * 解析中文地址文本
     *
     * @param apiKey 开发者 API Key
     * @param text   待解析文本,最大 200 字符
     * @return data 节点;解析失败返回 null,且不收费
     */
    public static JSONObject parse(String apiKey, String text) {
        JSONObject json = JSONUtil.parseObj(
                HttpRequest.post(API_URL)
                        .header("X-API-Key", apiKey)
                        .body(JSONUtil.createObj().set("text", text).toString())
                        .timeout(20000)
                        .execute().body());
        if (json.getInt("code") == null || json.getInt("code") != 0) {
            System.out.println("解析失败(不收费):" + json.getStr("msg"));
            return null;
        }
        return json.getJSONObject("data");
    }

    public static void main(String[] args) {
        JSONObject data = parse("你的APIKey", "张三,13020260925,重庆市铜梁区白龙大道龙腾盛世");
        if (data == null) {
            return;
        }
        System.out.printf("%s %s %s %s%n",
                data.getStr("provinceCode"), data.getStr("cityCode"),
                data.getStr("districtCode"), data.getStr("zipCode"));
    }
}

4.3 Python

import requests


def address_parse(api_key: str, text: str):
    """返回 data 节点;解析失败返回 None,且不收费"""
    resp = requests.post(
        "https://api.xujian.tech/openapi/address/parse",
        json={"text": text},
        headers={"X-API-Key": api_key},
        timeout=20,
    )
    result = resp.json()
    if result.get("code") != 0:
        print("解析失败(不收费):", result.get("msg"))
        return None
    return result["data"]


if __name__ == "__main__":
    print(address_parse("你的APIKey", "李四 13800138000 四川省成都市郫都区红光镇家园路88号"))

4.4 JavaScript

async function addressParse(apiKey, text) {
  const resp = await fetch("https://api.xujian.tech/openapi/address/parse", {
    method: "POST",
    headers: { "X-API-Key": apiKey, "Content-Type": "application/json" },
    body: JSON.stringify({ text })
  });
  const result = await resp.json();
  if (result.code !== 0) {
    throw new Error(result.msg);
  }
  return result.data;
}

五、返回示例

直辖市地址:

{
  "code": 0,
  "msg": "success",
  "data": {
    "name": "张三",
    "phone": "13020260925",
    "address": "重庆市铜梁区白龙大道龙腾盛世",
    "province": "重庆市",
    "provinceCode": "500000",
    "city": "重庆市",
    "cityCode": "500000",
    "district": "铜梁区",
    "districtCode": "500151",
    "detail": "白龙大道龙腾盛世",
    "zipCode": "402500",
    "apiCode": "address.parse",
    "apiName": "地址信息解析",
    "chargeType": "PER_CALL",
    "balance": 99.9800,
    "costMs": 1820
  }
}

只写到市(区县与邮编返回空字符串):

{
  "code": 0,
  "msg": "success",
  "data": {
    "name": "",
    "phone": "",
    "address": "浙江省杭州市文一西路969号",
    "province": "浙江省",
    "provinceCode": "330000",
    "city": "杭州市",
    "cityCode": "330100",
    "district": "",
    "districtCode": "",
    "detail": "文一西路969号",
    "zipCode": "",
    "apiCode": "address.parse",
    "apiName": "地址信息解析",
    "chargeType": "PER_CALL",
    "balance": 99.9400,
    "costMs": 1410
  }
}

省直辖县级行政区(districtCode 为 9 位):

{
  "code": 0,
  "msg": "success",
  "data": {
    "name": "王五",
    "phone": "13900139000",
    "address": "河南省济源市黄河大道88号",
    "province": "河南省",
    "provinceCode": "410000",
    "city": "济源市",
    "cityCode": "419001",
    "district": "济源市",
    "districtCode": "419001000",
    "detail": "黄河大道88号",
    "zipCode": "459000",
    "apiCode": "address.parse",
    "apiName": "地址信息解析",
    "chargeType": "PER_CALL",
    "balance": 99.9200,
    "costMs": 1670
  }
}

解析失败(不收费):

{
  "code": 500,
  "msg": "未能从文本中识别出有效地址(至少需要能定位到省级行政区),请补充更完整的地址后重试;本次调用不计费",
  "data": null
}

六、可直接复用的两段代码

6.1 批量清洗 + 进度保存

import json
import time

import requests


def batch_clean(api_key: str, rows, out_file: str, sleep: float = 0.2):
    """rows: [{'id': 1, 'raw': '张三 130... 重庆市...'}, ...],断点续跑"""
    done = set()
    try:
        with open(out_file, encoding="utf-8") as f:
            for line in f:
                done.add(json.loads(line)["id"])
    except FileNotFoundError:
        pass

    with open(out_file, "a", encoding="utf-8") as f:
        for row in rows:
            if row["id"] in done:
                continue
            data = address_parse(api_key, row["raw"][:200])
            if data:
                f.write(json.dumps({
                    "id": row["id"],
                    "province_code": data["provinceCode"],
                    "city_code": data["cityCode"],
                    "district_code": data["districtCode"],
                    "zip_code": data["zipCode"],
                    "detail": data["detail"],
                }, ensure_ascii=False) + "\n")
                f.flush()
            time.sleep(sleep)

6.2 清洗质量统计

def quality_report(results):
    """results 为清洗结果列表,统计各级命中率"""
    total = len(results) or 1
    def hit(key):
        return sum(1 for r in results if r.get(key)) / total
    return {
        "province": hit("province_code"),
        "city": hit("city_code"),
        "district": hit("district_code"),
        "zip": hit("zip_code"),
    }

七、实践建议

  1. 超长文本先本地截断。text 上限 200 字符,超了直接失败且不收费,批量任务里先切到 200 再发。
  2. 用 districtCode 做外键,不要用地名。地名有简称、别名,adcode 稳定。
  3. 空字符串要兜底。区县、邮编经常为空(用户没写),下游逻辑别假设一定有值。
  4. 9 位代码要留够字段长度。省直辖县级行政区(如济源市)的 districtCode 是 9 位。
  5. 失败要分类。解析不出省级行政区是数据问题,服务超时是可用性问题,两类应该分别统计、分别重试。
  6. 批量任务加缓存。同一地址文本重复出现很常见,先查本地缓存能省不少调用。
  7. 1 ~ 5 秒的耗时要有预期。含一轮语义抽取,批量任务建议低并发 + 退避重试。
  8. 结果存原始文本。保留 raw 与解析结果,方便以后口径升级后重跑。

八、错误码与排查

九、计费与接入

接入流程:注册开发者账号 → 控制台创建 API Key → 请求头带上 X-API-Key 即可调用,无需签名或加密。控制台可查看调用量、扣费流水与余额。

服务站点:api.xujian.tech(纯文本域名,不做跳转)。接口试用、数据与充值咨询可在控制台提交工单,或联系 Vxujian_cq。

十、小结

地址清洗的价值不在「拆字段」,而在拆完之后能按区域做统计、匹配运费、判断配送范围。address.parse 的几个关键取舍:

  • 解析不出省级不收费:批量治理脏数据时,失败不产生成本;
  • 字段口径统一:三级名称 + 6 位 adcode + 邮编,直接落库当维表用;
  • GET / POST 都支持:批量脚本用 POST,前端表单用 GET,不用改服务端;
  • 空值是空字符串不是 null:解析代码里判断要统一,别写成 is None。

如果只想要标准行政区划数据本身(不含姓名电话),可以搭配行政区划查询接口 region.query(免费)使用:用它做本地底库,用本接口做文本解析。

扫码添加微信
联系作者 · 微信二维码

微信号:xujian_cq

接口对接、充值 / 授权、定制需求都可以直接聊