Skip to main content

geoalign

Map Chinese administrative-division names (county level and above) to official codes, and convert codes between years 2012–2025.

把中国县级以上行政区划的名称写法对到官方代码,并在 2012 至 2025 年之间换算代码。

  • Data / 数据: WorldInsightLab/china-admin-divisions
  • License / 许可: code Apache-2.0 (LICENSE); third-party notices in NOTICE / 代码 Apache-2.0,第三方声明见 NOTICE
  • Source / 源码: World-Insight-Lab/geoalign · PyPI: geoalign
  • Version / 版本: 0.1.1 (0.1.1 changes package metadata only; code and data are the same as 0.1.0 / 0.1.1 只改了包的元数据,代码和数据与 0.1.0 相同)

English · 中文


English

What it does

  1. Turns a written place name into an administrative-division code. You can give a year and a parent name.
  2. Converts a code from one year to another. For splits and mergers it returns every destination.
  3. Shows the history of a code.

When the library is not sure, it returns no code and lists all candidates instead.

Install

From PyPI:

pip install geoalign

Or from the wheel in the dataset repository:

pip install https://huggingface.co/datasets/WorldInsightLab/china-admin-divisions/resolve/main/geoalign/dist/geoalign-0.1.1-py3-none-any.whl

From source (run in the geoalign/ directory, where pyproject.toml is):

pip install .
  • Lookup and the typo rules use only the Python standard library (Python 3.8+). No GPU.
  • The embedding fallback is optional. It needs sentence-transformers and torch (from source: pip install ".[embed]"), and you need to supply a Chinese embedding model yourself. The public benchmark does not cover the embedding fallback.

Scope

  1. Year-end code tables for 2012–2025, county level and above, all from official Ministry of Civil Affairs (MCA) pages. The data and its sources are described in the dataset card.
  2. If the year is earlier than 2012, the library gives no code, and note says the data starts in 2012.
  3. If the year is later than 2025, the 2025 table is used.
  4. County level and above only. Do not pass township names. After removing generic suffixes such as 镇, 乡, 街道, 1,358 of 27,004 distinct township spellings (5.0%) are confidently matched to a county-level-or-above unit (e.g. “三台” → 三台县). Counted per township (a name that occurs in several places counts each time), about 12% of 38,742 townships (4,497) are matched this way. The matched unit is often not the county that contains the township.

Usage

The outputs below were produced by the wheel above, installed in a clean virtual environment.

from geoalign import Gazetteer
g = Gazetteer()

m = g.align("密云县")                     # no year: map to the latest code
(m.code, m.name, m.confidence, m.method, m.year)
# ('110118', '密云区', 'medium', 'history', 2025)

g.align("密云县", year=2013).code         # '110228' — still 密云县 at the end of 2013
g.align("朝阳区", parent="长春市").code    # '220104'

m = g.align("朝阳区")                     # duplicate name, no parent
(m.code, m.best, m.confidence, m.method)
# (None, '110105', 'low', 'exact')        # not sure: no code
[(c.code, c.name, c.parent_name) for c in m.candidates]
# [('110105', '朝阳区', '北京市'), ('220104', '朝阳区', '吉林省长春市')]

m = g.align("天水市麦积区")                # parent and name written together
(m.code, m.name, m.confidence, m.method)
# ('620503', '麦积区', 'medium', 'split')

m = g.align("密云县", year=1990)           # earlier than 2012
(m.code, m.confidence)
# (None, 'low')

g.to_year("110228", 2025)
# YearResult(codes=['110118'], names=['密云区'], exact=True,
#            steps=['2014→2015:110228 密云县 → 110118 密云区(撤县设区)'])

g.to_year("130103", 2016)                 # 石家庄 桥东区, split in 2014
# YearResult(codes=['130102', '130104'], names=['长安区', '桥西区'], exact=False,
#            steps=['2014→2015:130103 桥东区 → 130102 长安区(拆分)',
#                   '2014→2015:130103 桥东区 → 130104 桥西区(拆分)'])

g.history("330103")                       # 杭州 下城区, merged into 拱墅区 in 2021
# {'code': '330103', 'names': [{'name': '下城区', 'from': 2012, 'to': 2020}],
#  'events': [{'year': 2021, 'type': '合并', 'relation': '多对一', 'partial': False,
#              'old_code': '330103', 'old_name': '下城区', 'new_code': '330105', 'new_name': '拱墅区',
#              'basis': '官方变更情况', 'source_url': 'http://xzqh.mca.gov.cn/description?dcpid=2021'}]}

Fields returned by align:

Field Meaning
code The code when the library is sure; otherwise None
best The top candidate. Given even when not sure, for callers that must pick one
name Standard name of code or best
confidence high: unique full name. medium: unique after short form, former name, or splitting a parent+name string. low: typo rules, embedding, found only after dropping the parent, several candidates, generic name, or year before 2012. none: not found
method exact, alias, history, split, no_parent, fuzzy, embedding, none
candidates All candidates. For duplicate names, all units with that name
year The year of the table used
source_grade Source grade of that year's table. In this release always A (official page)
rebuilt Whether that year's table was rebuilt. In this release always False
note Extra explanation

When confidence is low or none, code is None.

Generic names (“市区”, “新区”, “城区”, “郊区”, “矿区”, “东区”, “西区”, etc.) on their own get at most low. If a parent is given and it narrows the name to one unit (e.g. parent “长治市” + “城区”), a code is given as usual.

Lookup order

  1. Normalize: strip whitespace and leading/trailing punctuation, full-width to half-width. A parent such as “市辖区” is treated as not given.
  2. Choose the table year. Without a year, the latest year is used.
  3. In that year's table, look for the full name, then short forms (generic suffix removed; short forms of ethnic autonomous areas and banners; ethnic district names without the ethnic group). Filter by parent when given. A short form of one character is not used.
  4. If not in that year's table: search all years, then follow the official change table to that year. For splits, follow the main successor (main = 是 in the change table). When the notice names no main successor, return all destinations and no code.
  5. If still not found: check whether parent and name are written together (天水市麦积区), split, and search again.
  6. If a parent was given and nothing is found: search again without the parent.
  7. Typo rules (geoalign/fuzzy.py): homophones and similar-looking characters. low only.
  8. Embedding model (optional, geoalign/embed.py). low only.

Public benchmark

The benchmark is in benchmark/: make_questions.py generates the questions and run.py scores them. Questions use only the official code tables and notice sentences in the dataset, built by the rules written at the top of make_questions.py. Answers follow the year-end convention.

Results (benchmark/results.md; lookup and typo rules only, no embedding model). We re-ran run.py against the installed wheel and got the same table.

Question type Questions Share given a code Accuracy when a code is given
Former name from a notice, with year 224 100.0% 100.0%
Abolished name from a notice, no year (answer: 2025 code) 198 100.0% 100.0%
“Parent + name” written together in a notice 210 100.0% 100.0%
Full name, with year 299 100.0% 100.0%
Full name, no year 100 100.0% 100.0%
Short form (trailing 市, 县, 区, 旗, 地区, 矿区 removed) 323 100.0% 100.0%
Short form of ethnic autonomous areas 112 100.0% 100.0%
Parent full name + full name 210 100.0% 100.0%
Duplicate name, parent given 84 100.0% 100.0%
All questions with an answer 1,760 100.0% 100.0%

On the 180 questions whose correct answer is “give no code” (duplicate name without parent, short form matching several units, year before 2012, generic name, unit created in 2026), the library gave a code 0 times.

This benchmark is easy and does not show performance on real data. The rules that generate the questions (remove trailing 市/县/区/旗, remove the ethnic group name, parent + full name) are essentially the same as the library's short-form and split rules, so near-100% in these categories is expected. The benchmark mainly checks that the rules are implemented correctly and that the library does not guess on duplicate names. All spellings are official or derived by simple rules: there are no typos and no messy spellings. Real data has typos, truncated names and township names mixed in. On such data the share given a code will be much lower, and given codes can be wrong. The typo rules have no public benchmark.

Data files

The files in geoalign/data/ are produced by two scripts:

  1. python -m geoalign.build_data <dataset data directory> packs the code tables and the change table. It checks the scope: code tables from 2012, change table from 2013.
  2. python tools/build_confusion.py <years.csv> <NotoSansCJK-Regular.ttc> builds the homophone and similar-character tables for the typo rules. Only this step needs Pillow, numpy, pypinyin and the Noto Sans CJK font.

Tests

python -m unittest discover -s tests

License

Code: Apache-2.0, see LICENSE. The pinyin in geoalign/data/confusion.json was generated with pypinyin (data from pinyin-data, both MIT). The similar-looking character pairs were computed by rendering characters with the Noto Sans CJK font (SIL OFL 1.1); the font is not included. Copyright notices and licenses are in NOTICE. The data in geoalign/data/ comes from the dataset; see the dataset card for its license (CC BY 4.0 for the compilation and annotations).


中文

做什么

  1. 把地名写法变成行政区划代码。可以给年份和上级地名。
  2. 把一年的代码换成另一年的代码。拆分、合并时给出全部去向。
  3. 查一个地方的沿革。

没有把握时,工具库不给代码,给全部候选。

安装

从 PyPI 安装:

pip install geoalign

也可以从数据集仓库里的 wheel 安装:

pip install https://huggingface.co/datasets/WorldInsightLab/china-admin-divisions/resolve/main/geoalign/dist/geoalign-0.1.1-py3-none-any.whl

从源码安装(在 pyproject.toml 所在的 geoalign/ 目录下运行):

pip install .
  • 查表和错别字规则只用 Python 标准库(Python 3.8 以上),不用显卡。
  • 向量模型后备是可选的。要装 sentence-transformers 和 torch(从源码装时可用 pip install ".[embed]"),还要自己准备一个中文向量模型。公开测试题不测向量模型后备。

数据范围

  1. 2012 至 2025 年,每年年底的县级以上代码表,全部来自民政部官方页。数据和出处见数据集卡片。
  2. 给的年份早于 2012 年时,工具库不给代码,note 写明“数据只从 2012 年开始”。
  3. 给的年份晚于 2025 年时,用 2025 年的表。
  4. 只管县级以上。不要把乡镇名交给工具库。 去掉“镇、乡、街道”等通名以后,27,004 个不同的乡镇写法里有 1,358 个(5.0%)会被有把握地认成县级以上单位(例:“三台”→三台县)。按乡镇个数算(同名乡镇按出现次数算),38,742 个乡镇里约 12%(4,497 个)会被这样认错。认出的单位常常不是这个乡镇所在的县。

用法

下面的输出由上面的 wheel 在干净的虚拟环境里实际运行得到。

from geoalign import Gazetteer
g = Gazetteer()

m = g.align("密云县")                     # 不给年份时,对到最新的代码
(m.code, m.name, m.confidence, m.method, m.year)
# ('110118', '密云区', 'medium', 'history', 2025)

g.align("密云县", year=2013).code         # '110228':2013 年底还是密云县
g.align("朝阳区", parent="长春市").code    # '220104'

m = g.align("朝阳区")                     # 重名,没有上级
(m.code, m.best, m.confidence, m.method)
# (None, '110105', 'low', 'exact')        # 没有把握,不给代码
[(c.code, c.name, c.parent_name) for c in m.candidates]
# [('110105', '朝阳区', '北京市'), ('220104', '朝阳区', '吉林省长春市')]

m = g.align("天水市麦积区")                # 上级和本级连写
(m.code, m.name, m.confidence, m.method)
# ('620503', '麦积区', 'medium', 'split')

m = g.align("密云县", year=1990)           # 早于 2012 年
(m.code, m.confidence)
# (None, 'low')

g.to_year("110228", 2025)
# YearResult(codes=['110118'], names=['密云区'], exact=True,
#            steps=['2014→2015:110228 密云县 → 110118 密云区(撤县设区)'])

g.to_year("130103", 2016)                 # 石家庄桥东区 2014 年撤销,分给两个区
# YearResult(codes=['130102', '130104'], names=['长安区', '桥西区'], exact=False,
#            steps=['2014→2015:130103 桥东区 → 130102 长安区(拆分)',
#                   '2014→2015:130103 桥东区 → 130104 桥西区(拆分)'])

g.history("330103")                       # 杭州市下城区:2021 年并入拱墅区
# {'code': '330103', 'names': [{'name': '下城区', 'from': 2012, 'to': 2020}],
#  'events': [{'year': 2021, 'type': '合并', 'relation': '多对一', 'partial': False,
#              'old_code': '330103', 'old_name': '下城区', 'new_code': '330105', 'new_name': '拱墅区',
#              'basis': '官方变更情况', 'source_url': 'http://xzqh.mca.gov.cn/description?dcpid=2021'}]}

align 返回的字段:

字段 意思
code 有把握时的代码。没有把握时是 None
best 排第一的候选。没有把握时也给,供必须取一个的调用方用
name code 或 best 的标准名称
confidence high:全称唯一。medium:简称、旧名、连写拆开以后唯一。low:错别字规则、向量模型、去掉上级才找到、有多个候选、泛称、早于 2012 年。none:找不到
method exact、alias、history、split、no_parent、fuzzy、embedding、none
candidates 全部候选。重名时是全部重名单位
year 用的哪一年的表
source_grade 这一年的表的来源等级。本版只有 A(官方原页)
rebuilt 这一年的表是不是重建的。本版都是 False
note 补充说明

confidence 是 low 或 none 时,code 是 None。

泛称(“市区”“新区”“城区”“郊区”“矿区”“东区”“西区”等)单独出现时最多给 low。给了上级、上级把它确定成一个单位时(例:上级“长治市”+“城区”),照常给代码。

查的顺序

  1. 规范写法:去空白、首尾标点,全角换半角。“市辖区”这类上级当作没给。
  2. 定用哪一年的表。不给年份时用最新一年。
  3. 在这一年的表里找全称,再找简称(去掉通名、民族自治地方的简称、旗的简称、民族区去掉民族名)。给了上级时用上级筛。去掉通名后只剩 1 个字的不作简称。
  4. 这一年的表里没有:到所有年份找,再沿官方变更表换成这一年的代码。拆分时沿主要承继走(变更表 main = 是)。公告没有说主要承继时,给全部去向,不给代码。
  5. 还没有:看是不是上级和本级连写(天水市麦积区),拆开再找。
  6. 给了上级还找不到:去掉上级再找。
  7. 错别字规则(geoalign/fuzzy.py):同音字、形近字。只给 low。
  8. 向量模型(可选,geoalign/embed.py)。只给 low。

公开测试题

公开测试题在 benchmark/:make_questions.py 生成题目,run.py 测。题目只用数据集里的官方代码表和公告原句,按写明的规则生成,答案按年底口径。生成规则写在 make_questions.py 开头。

结果(benchmark/results.md,只查表和错别字规则,不用向量模型)。我们用安装好的 wheel 重跑 run.py,结果和这张表相同。

题的种类 题数 给代码的比例 给代码时的正确率
公告里的旧名称,给年份 224 100.0% 100.0%
公告里撤销的旧名称,不给年份(答案是 2025 年的代码) 198 100.0% 100.0%
公告里的“上级 + 名称”连写 210 100.0% 100.0%
全称,给年份 299 100.0% 100.0%
全称,不给年份 100 100.0% 100.0%
简称(去掉末尾的市、县、区、旗、地区、矿区) 323 100.0% 100.0%
民族自治地方的简称 112 100.0% 100.0%
上级全称 + 全称 210 100.0% 100.0%
重名,给了上级 84 100.0% 100.0%
有答案的题合计 1,760 100.0% 100.0%

答案是“不应给代码”的 180 道题(重名没给上级、简称对得上几个单位、早于 2012 年、泛称、2026 年才设立的单位),错给代码 0 道。

这套题容易,不代表真实数据上的成绩。 出题的变形规则(去掉末尾的市、县、区、旗,去掉民族名,上级 + 全称)和工具库的简称、连写规则基本相同,所以这些类别接近 100% 是预期的。这套题主要检验规则的实现没有错、重名时不乱给代码。题里的写法都是官方写法或按简单规则变出来的,没有错别字,没有乱写法。真实数据里有错别字、残缺的名称、乡镇名混入。在这类数据上,给代码的比例会低得多,给代码时也可能出错。错别字规则没有公开测试题。

数据文件

geoalign/data/ 里的文件由下面两个脚本生成:

  1. python -m geoalign.build_data <数据集的 data 目录>:打包代码表和变更表。脚本检查范围:代码表只收 2012 年及以后,变更表只收 2013 年及以后。
  2. python tools/build_confusion.py <years.csv> <NotoSansCJK-Regular.ttc>:生成错别字规则用的同音字、形近字表。只在生成时要 Pillow、numpy、pypinyin 和 Noto Sans CJK 字体。

测试

python -m unittest discover -s tests

许可

代码按 Apache-2.0 许可发布,见 LICENSE。错别字字表 geoalign/data/confusion.json 里的拼音由 pypinyin 生成(数据来自 pinyin-data,都是 MIT 许可),形近字用 Noto Sans CJK 字体(SIL OFL 1.1)画图算出,包里不带字体。版权声明和许可见 NOTICE。geoalign/data/ 里的数据来自数据集,许可见数据集卡片(编排和标注按 CC BY 4.0)。

Metadata

Release files for geoalign 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for geoalign 0.1.1
File Size Uploaded Provenance Actions
geoalign-0.1.1.tar.gz 569.1 kB Without provenance Details for geoalign-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for geoalign 0.1.1
File Interpreter ABI Platform Actions
geoalign-0.1.1-py3-none-any.whl Python 3 none any Details for geoalign-0.1.1-py3-none-any.whl

Total release size: 1.1 MB

Release files / geoalign-0.1.1.tar.gz

Download URL geoalign-0.1.1.tar.gz
Size 569.1 kB
Tags Source
SHA-256 checksum
How to use checksums
4ae6af6dcffe23e8ddb69553ea83542cffed3b20589c668d1ca37d139f8b4b0c
BLAKE2b-256 checksum
How to use checksums
8c9f2f628805eeb7eafbb6cc13a50a2a6b3c0e46b25f4d8d7383a87c0e250dc6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.3

Release files / geoalign-0.1.1-py3-none-any.whl

Download URL geoalign-0.1.1-py3-none-any.whl
Size 566.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
eae60ca59c917b29a49c819243ea7ddc8045a9d3eea7e702da58fc718bf9e992
BLAKE2b-256 checksum
How to use checksums
70699f899c8f37ff24491820fef133a19b196511319e49f83d5ed1c7bc47c1fc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.3

Security for geoalign 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page