Datasets:
First release: year-end tables 2012-2025, changes 2013-2025, geoalign 0.1.0
Browse files- .gitattributes +1 -0
- LICENSE +396 -0
- README.md +568 -0
- data/changes.csv +0 -0
- data/corrections_applied.csv +0 -0
- data/years.csv +0 -0
- geoalign/LICENSE +202 -0
- geoalign/NOTICE +56 -0
- geoalign/README.md +313 -0
- geoalign/benchmark/make_questions.py +193 -0
- geoalign/benchmark/questions.csv +0 -0
- geoalign/benchmark/results.md +21 -0
- geoalign/benchmark/run.py +52 -0
- geoalign/dist/geoalign-0.1.0-py3-none-any.whl +3 -0
- geoalign/dist/geoalign-0.1.0.tar.gz +3 -0
- geoalign/geoalign/__init__.py +4 -0
- geoalign/geoalign/build_data.py +45 -0
- geoalign/geoalign/core.py +429 -0
- geoalign/geoalign/data/changes.csv.gz +3 -0
- geoalign/geoalign/data/confusion.json +0 -0
- geoalign/geoalign/data/years.csv.gz +3 -0
- geoalign/geoalign/data/years_meta.json +100 -0
- geoalign/geoalign/embed.py +64 -0
- geoalign/geoalign/fuzzy.py +79 -0
- geoalign/pyproject.toml +26 -0
- geoalign/tests/test_geoalign.py +212 -0
- geoalign/tools/build_confusion.py +87 -0
.gitattributes
CHANGED
|
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
+
geoalign/dist/geoalign-0.1.0-py3-none-any.whl filter=lfs diff=lfs merge=lfs -text
|
LICENSE
ADDED
|
@@ -0,0 +1,396 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Attribution 4.0 International
|
| 2 |
+
|
| 3 |
+
=======================================================================
|
| 4 |
+
|
| 5 |
+
Creative Commons Corporation ("Creative Commons") is not a law firm and
|
| 6 |
+
does not provide legal services or legal advice. Distribution of
|
| 7 |
+
Creative Commons public licenses does not create a lawyer-client or
|
| 8 |
+
other relationship. Creative Commons makes its licenses and related
|
| 9 |
+
information available on an "as-is" basis. Creative Commons gives no
|
| 10 |
+
warranties regarding its licenses, any material licensed under their
|
| 11 |
+
terms and conditions, or any related information. Creative Commons
|
| 12 |
+
disclaims all liability for damages resulting from their use to the
|
| 13 |
+
fullest extent possible.
|
| 14 |
+
|
| 15 |
+
Using Creative Commons Public Licenses
|
| 16 |
+
|
| 17 |
+
Creative Commons public licenses provide a standard set of terms and
|
| 18 |
+
conditions that creators and other rights holders may use to share
|
| 19 |
+
original works of authorship and other material subject to copyright
|
| 20 |
+
and certain other rights specified in the public license below. The
|
| 21 |
+
following considerations are for informational purposes only, are not
|
| 22 |
+
exhaustive, and do not form part of our licenses.
|
| 23 |
+
|
| 24 |
+
Considerations for licensors: Our public licenses are
|
| 25 |
+
intended for use by those authorized to give the public
|
| 26 |
+
permission to use material in ways otherwise restricted by
|
| 27 |
+
copyright and certain other rights. Our licenses are
|
| 28 |
+
irrevocable. Licensors should read and understand the terms
|
| 29 |
+
and conditions of the license they choose before applying it.
|
| 30 |
+
Licensors should also secure all rights necessary before
|
| 31 |
+
applying our licenses so that the public can reuse the
|
| 32 |
+
material as expected. Licensors should clearly mark any
|
| 33 |
+
material not subject to the license. This includes other CC-
|
| 34 |
+
licensed material, or material used under an exception or
|
| 35 |
+
limitation to copyright. More considerations for licensors:
|
| 36 |
+
wiki.creativecommons.org/Considerations_for_licensors
|
| 37 |
+
|
| 38 |
+
Considerations for the public: By using one of our public
|
| 39 |
+
licenses, a licensor grants the public permission to use the
|
| 40 |
+
licensed material under specified terms and conditions. If
|
| 41 |
+
the licensor's permission is not necessary for any reason--for
|
| 42 |
+
example, because of any applicable exception or limitation to
|
| 43 |
+
copyright--then that use is not regulated by the license. Our
|
| 44 |
+
licenses grant only permissions under copyright and certain
|
| 45 |
+
other rights that a licensor has authority to grant. Use of
|
| 46 |
+
the licensed material may still be restricted for other
|
| 47 |
+
reasons, including because others have copyright or other
|
| 48 |
+
rights in the material. A licensor may make special requests,
|
| 49 |
+
such as asking that all changes be marked or described.
|
| 50 |
+
Although not required by our licenses, you are encouraged to
|
| 51 |
+
respect those requests where reasonable. More considerations
|
| 52 |
+
for the public:
|
| 53 |
+
wiki.creativecommons.org/Considerations_for_licensees
|
| 54 |
+
|
| 55 |
+
=======================================================================
|
| 56 |
+
|
| 57 |
+
Creative Commons Attribution 4.0 International Public License
|
| 58 |
+
|
| 59 |
+
By exercising the Licensed Rights (defined below), You accept and agree
|
| 60 |
+
to be bound by the terms and conditions of this Creative Commons
|
| 61 |
+
Attribution 4.0 International Public License ("Public License"). To the
|
| 62 |
+
extent this Public License may be interpreted as a contract, You are
|
| 63 |
+
granted the Licensed Rights in consideration of Your acceptance of
|
| 64 |
+
these terms and conditions, and the Licensor grants You such rights in
|
| 65 |
+
consideration of benefits the Licensor receives from making the
|
| 66 |
+
Licensed Material available under these terms and conditions.
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
Section 1 -- Definitions.
|
| 70 |
+
|
| 71 |
+
a. Adapted Material means material subject to Copyright and Similar
|
| 72 |
+
Rights that is derived from or based upon the Licensed Material
|
| 73 |
+
and in which the Licensed Material is translated, altered,
|
| 74 |
+
arranged, transformed, or otherwise modified in a manner requiring
|
| 75 |
+
permission under the Copyright and Similar Rights held by the
|
| 76 |
+
Licensor. For purposes of this Public License, where the Licensed
|
| 77 |
+
Material is a musical work, performance, or sound recording,
|
| 78 |
+
Adapted Material is always produced where the Licensed Material is
|
| 79 |
+
synched in timed relation with a moving image.
|
| 80 |
+
|
| 81 |
+
b. Adapter's License means the license You apply to Your Copyright
|
| 82 |
+
and Similar Rights in Your contributions to Adapted Material in
|
| 83 |
+
accordance with the terms and conditions of this Public License.
|
| 84 |
+
|
| 85 |
+
c. Copyright and Similar Rights means copyright and/or similar rights
|
| 86 |
+
closely related to copyright including, without limitation,
|
| 87 |
+
performance, broadcast, sound recording, and Sui Generis Database
|
| 88 |
+
Rights, without regard to how the rights are labeled or
|
| 89 |
+
categorized. For purposes of this Public License, the rights
|
| 90 |
+
specified in Section 2(b)(1)-(2) are not Copyright and Similar
|
| 91 |
+
Rights.
|
| 92 |
+
|
| 93 |
+
d. Effective Technological Measures means those measures that, in the
|
| 94 |
+
absence of proper authority, may not be circumvented under laws
|
| 95 |
+
fulfilling obligations under Article 11 of the WIPO Copyright
|
| 96 |
+
Treaty adopted on December 20, 1996, and/or similar international
|
| 97 |
+
agreements.
|
| 98 |
+
|
| 99 |
+
e. Exceptions and Limitations means fair use, fair dealing, and/or
|
| 100 |
+
any other exception or limitation to Copyright and Similar Rights
|
| 101 |
+
that applies to Your use of the Licensed Material.
|
| 102 |
+
|
| 103 |
+
f. Licensed Material means the artistic or literary work, database,
|
| 104 |
+
or other material to which the Licensor applied this Public
|
| 105 |
+
License.
|
| 106 |
+
|
| 107 |
+
g. Licensed Rights means the rights granted to You subject to the
|
| 108 |
+
terms and conditions of this Public License, which are limited to
|
| 109 |
+
all Copyright and Similar Rights that apply to Your use of the
|
| 110 |
+
Licensed Material and that the Licensor has authority to license.
|
| 111 |
+
|
| 112 |
+
h. Licensor means the individual(s) or entity(ies) granting rights
|
| 113 |
+
under this Public License.
|
| 114 |
+
|
| 115 |
+
i. Share means to provide material to the public by any means or
|
| 116 |
+
process that requires permission under the Licensed Rights, such
|
| 117 |
+
as reproduction, public display, public performance, distribution,
|
| 118 |
+
dissemination, communication, or importation, and to make material
|
| 119 |
+
available to the public including in ways that members of the
|
| 120 |
+
public may access the material from a place and at a time
|
| 121 |
+
individually chosen by them.
|
| 122 |
+
|
| 123 |
+
j. Sui Generis Database Rights means rights other than copyright
|
| 124 |
+
resulting from Directive 96/9/EC of the European Parliament and of
|
| 125 |
+
the Council of 11 March 1996 on the legal protection of databases,
|
| 126 |
+
as amended and/or succeeded, as well as other essentially
|
| 127 |
+
equivalent rights anywhere in the world.
|
| 128 |
+
|
| 129 |
+
k. You means the individual or entity exercising the Licensed Rights
|
| 130 |
+
under this Public License. Your has a corresponding meaning.
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
Section 2 -- Scope.
|
| 134 |
+
|
| 135 |
+
a. License grant.
|
| 136 |
+
|
| 137 |
+
1. Subject to the terms and conditions of this Public License,
|
| 138 |
+
the Licensor hereby grants You a worldwide, royalty-free,
|
| 139 |
+
non-sublicensable, non-exclusive, irrevocable license to
|
| 140 |
+
exercise the Licensed Rights in the Licensed Material to:
|
| 141 |
+
|
| 142 |
+
a. reproduce and Share the Licensed Material, in whole or
|
| 143 |
+
in part; and
|
| 144 |
+
|
| 145 |
+
b. produce, reproduce, and Share Adapted Material.
|
| 146 |
+
|
| 147 |
+
2. Exceptions and Limitations. For the avoidance of doubt, where
|
| 148 |
+
Exceptions and Limitations apply to Your use, this Public
|
| 149 |
+
License does not apply, and You do not need to comply with
|
| 150 |
+
its terms and conditions.
|
| 151 |
+
|
| 152 |
+
3. Term. The term of this Public License is specified in Section
|
| 153 |
+
6(a).
|
| 154 |
+
|
| 155 |
+
4. Media and formats; technical modifications allowed. The
|
| 156 |
+
Licensor authorizes You to exercise the Licensed Rights in
|
| 157 |
+
all media and formats whether now known or hereafter created,
|
| 158 |
+
and to make technical modifications necessary to do so. The
|
| 159 |
+
Licensor waives and/or agrees not to assert any right or
|
| 160 |
+
authority to forbid You from making technical modifications
|
| 161 |
+
necessary to exercise the Licensed Rights, including
|
| 162 |
+
technical modifications necessary to circumvent Effective
|
| 163 |
+
Technological Measures. For purposes of this Public License,
|
| 164 |
+
simply making modifications authorized by this Section 2(a)
|
| 165 |
+
(4) never produces Adapted Material.
|
| 166 |
+
|
| 167 |
+
5. Downstream recipients.
|
| 168 |
+
|
| 169 |
+
a. Offer from the Licensor -- Licensed Material. Every
|
| 170 |
+
recipient of the Licensed Material automatically
|
| 171 |
+
receives an offer from the Licensor to exercise the
|
| 172 |
+
Licensed Rights under the terms and conditions of this
|
| 173 |
+
Public License.
|
| 174 |
+
|
| 175 |
+
b. No downstream restrictions. You may not offer or impose
|
| 176 |
+
any additional or different terms or conditions on, or
|
| 177 |
+
apply any Effective Technological Measures to, the
|
| 178 |
+
Licensed Material if doing so restricts exercise of the
|
| 179 |
+
Licensed Rights by any recipient of the Licensed
|
| 180 |
+
Material.
|
| 181 |
+
|
| 182 |
+
6. No endorsement. Nothing in this Public License constitutes or
|
| 183 |
+
may be construed as permission to assert or imply that You
|
| 184 |
+
are, or that Your use of the Licensed Material is, connected
|
| 185 |
+
with, or sponsored, endorsed, or granted official status by,
|
| 186 |
+
the Licensor or others designated to receive attribution as
|
| 187 |
+
provided in Section 3(a)(1)(A)(i).
|
| 188 |
+
|
| 189 |
+
b. Other rights.
|
| 190 |
+
|
| 191 |
+
1. Moral rights, such as the right of integrity, are not
|
| 192 |
+
licensed under this Public License, nor are publicity,
|
| 193 |
+
privacy, and/or other similar personality rights; however, to
|
| 194 |
+
the extent possible, the Licensor waives and/or agrees not to
|
| 195 |
+
assert any such rights held by the Licensor to the limited
|
| 196 |
+
extent necessary to allow You to exercise the Licensed
|
| 197 |
+
Rights, but not otherwise.
|
| 198 |
+
|
| 199 |
+
2. Patent and trademark rights are not licensed under this
|
| 200 |
+
Public License.
|
| 201 |
+
|
| 202 |
+
3. To the extent possible, the Licensor waives any right to
|
| 203 |
+
collect royalties from You for the exercise of the Licensed
|
| 204 |
+
Rights, whether directly or through a collecting society
|
| 205 |
+
under any voluntary or waivable statutory or compulsory
|
| 206 |
+
licensing scheme. In all other cases the Licensor expressly
|
| 207 |
+
reserves any right to collect such royalties.
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
Section 3 -- License Conditions.
|
| 211 |
+
|
| 212 |
+
Your exercise of the Licensed Rights is expressly made subject to the
|
| 213 |
+
following conditions.
|
| 214 |
+
|
| 215 |
+
a. Attribution.
|
| 216 |
+
|
| 217 |
+
1. If You Share the Licensed Material (including in modified
|
| 218 |
+
form), You must:
|
| 219 |
+
|
| 220 |
+
a. retain the following if it is supplied by the Licensor
|
| 221 |
+
with the Licensed Material:
|
| 222 |
+
|
| 223 |
+
i. identification of the creator(s) of the Licensed
|
| 224 |
+
Material and any others designated to receive
|
| 225 |
+
attribution, in any reasonable manner requested by
|
| 226 |
+
the Licensor (including by pseudonym if
|
| 227 |
+
designated);
|
| 228 |
+
|
| 229 |
+
ii. a copyright notice;
|
| 230 |
+
|
| 231 |
+
iii. a notice that refers to this Public License;
|
| 232 |
+
|
| 233 |
+
iv. a notice that refers to the disclaimer of
|
| 234 |
+
warranties;
|
| 235 |
+
|
| 236 |
+
v. a URI or hyperlink to the Licensed Material to the
|
| 237 |
+
extent reasonably practicable;
|
| 238 |
+
|
| 239 |
+
b. indicate if You modified the Licensed Material and
|
| 240 |
+
retain an indication of any previous modifications; and
|
| 241 |
+
|
| 242 |
+
c. indicate the Licensed Material is licensed under this
|
| 243 |
+
Public License, and include the text of, or the URI or
|
| 244 |
+
hyperlink to, this Public License.
|
| 245 |
+
|
| 246 |
+
2. You may satisfy the conditions in Section 3(a)(1) in any
|
| 247 |
+
reasonable manner based on the medium, means, and context in
|
| 248 |
+
which You Share the Licensed Material. For example, it may be
|
| 249 |
+
reasonable to satisfy the conditions by providing a URI or
|
| 250 |
+
hyperlink to a resource that includes the required
|
| 251 |
+
information.
|
| 252 |
+
|
| 253 |
+
3. If requested by the Licensor, You must remove any of the
|
| 254 |
+
information required by Section 3(a)(1)(A) to the extent
|
| 255 |
+
reasonably practicable.
|
| 256 |
+
|
| 257 |
+
4. If You Share Adapted Material You produce, the Adapter's
|
| 258 |
+
License You apply must not prevent recipients of the Adapted
|
| 259 |
+
Material from complying with this Public License.
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
Section 4 -- Sui Generis Database Rights.
|
| 263 |
+
|
| 264 |
+
Where the Licensed Rights include Sui Generis Database Rights that
|
| 265 |
+
apply to Your use of the Licensed Material:
|
| 266 |
+
|
| 267 |
+
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
|
| 268 |
+
to extract, reuse, reproduce, and Share all or a substantial
|
| 269 |
+
portion of the contents of the database;
|
| 270 |
+
|
| 271 |
+
b. if You include all or a substantial portion of the database
|
| 272 |
+
contents in a database in which You have Sui Generis Database
|
| 273 |
+
Rights, then the database in which You have Sui Generis Database
|
| 274 |
+
Rights (but not its individual contents) is Adapted Material; and
|
| 275 |
+
|
| 276 |
+
c. You must comply with the conditions in Section 3(a) if You Share
|
| 277 |
+
all or a substantial portion of the contents of the database.
|
| 278 |
+
|
| 279 |
+
For the avoidance of doubt, this Section 4 supplements and does not
|
| 280 |
+
replace Your obligations under this Public License where the Licensed
|
| 281 |
+
Rights include other Copyright and Similar Rights.
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
|
| 285 |
+
|
| 286 |
+
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
|
| 287 |
+
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
|
| 288 |
+
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
|
| 289 |
+
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
|
| 290 |
+
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
|
| 291 |
+
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
| 292 |
+
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
|
| 293 |
+
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
|
| 294 |
+
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
|
| 295 |
+
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
|
| 296 |
+
|
| 297 |
+
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
|
| 298 |
+
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
|
| 299 |
+
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
|
| 300 |
+
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
|
| 301 |
+
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
|
| 302 |
+
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
|
| 303 |
+
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
|
| 304 |
+
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
|
| 305 |
+
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
|
| 306 |
+
|
| 307 |
+
c. The disclaimer of warranties and limitation of liability provided
|
| 308 |
+
above shall be interpreted in a manner that, to the extent
|
| 309 |
+
possible, most closely approximates an absolute disclaimer and
|
| 310 |
+
waiver of all liability.
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
Section 6 -- Term and Termination.
|
| 314 |
+
|
| 315 |
+
a. This Public License applies for the term of the Copyright and
|
| 316 |
+
Similar Rights licensed here. However, if You fail to comply with
|
| 317 |
+
this Public License, then Your rights under this Public License
|
| 318 |
+
terminate automatically.
|
| 319 |
+
|
| 320 |
+
b. Where Your right to use the Licensed Material has terminated under
|
| 321 |
+
Section 6(a), it reinstates:
|
| 322 |
+
|
| 323 |
+
1. automatically as of the date the violation is cured, provided
|
| 324 |
+
it is cured within 30 days of Your discovery of the
|
| 325 |
+
violation; or
|
| 326 |
+
|
| 327 |
+
2. upon express reinstatement by the Licensor.
|
| 328 |
+
|
| 329 |
+
For the avoidance of doubt, this Section 6(b) does not affect any
|
| 330 |
+
right the Licensor may have to seek remedies for Your violations
|
| 331 |
+
of this Public License.
|
| 332 |
+
|
| 333 |
+
c. For the avoidance of doubt, the Licensor may also offer the
|
| 334 |
+
Licensed Material under separate terms or conditions or stop
|
| 335 |
+
distributing the Licensed Material at any time; however, doing so
|
| 336 |
+
will not terminate this Public License.
|
| 337 |
+
|
| 338 |
+
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
|
| 339 |
+
License.
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
Section 7 -- Other Terms and Conditions.
|
| 343 |
+
|
| 344 |
+
a. The Licensor shall not be bound by any additional or different
|
| 345 |
+
terms or conditions communicated by You unless expressly agreed.
|
| 346 |
+
|
| 347 |
+
b. Any arrangements, understandings, or agreements regarding the
|
| 348 |
+
Licensed Material not stated herein are separate from and
|
| 349 |
+
independent of the terms and conditions of this Public License.
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
Section 8 -- Interpretation.
|
| 353 |
+
|
| 354 |
+
a. For the avoidance of doubt, this Public License does not, and
|
| 355 |
+
shall not be interpreted to, reduce, limit, restrict, or impose
|
| 356 |
+
conditions on any use of the Licensed Material that could lawfully
|
| 357 |
+
be made without permission under this Public License.
|
| 358 |
+
|
| 359 |
+
b. To the extent possible, if any provision of this Public License is
|
| 360 |
+
deemed unenforceable, it shall be automatically reformed to the
|
| 361 |
+
minimum extent necessary to make it enforceable. If the provision
|
| 362 |
+
cannot be reformed, it shall be severed from this Public License
|
| 363 |
+
without affecting the enforceability of the remaining terms and
|
| 364 |
+
conditions.
|
| 365 |
+
|
| 366 |
+
c. No term or condition of this Public License will be waived and no
|
| 367 |
+
failure to comply consented to unless expressly agreed to by the
|
| 368 |
+
Licensor.
|
| 369 |
+
|
| 370 |
+
d. Nothing in this Public License constitutes or may be interpreted
|
| 371 |
+
as a limitation upon, or waiver of, any privileges and immunities
|
| 372 |
+
that apply to the Licensor or You, including from the legal
|
| 373 |
+
processes of any jurisdiction or authority.
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
=======================================================================
|
| 377 |
+
|
| 378 |
+
Creative Commons is not a party to its public
|
| 379 |
+
licenses. Notwithstanding, Creative Commons may elect to apply one of
|
| 380 |
+
its public licenses to material it publishes and in those instances
|
| 381 |
+
will be considered the “Licensor.” The text of the Creative Commons
|
| 382 |
+
public licenses is dedicated to the public domain under the CC0 Public
|
| 383 |
+
Domain Dedication. Except for the limited purpose of indicating that
|
| 384 |
+
material is shared under a Creative Commons public license or as
|
| 385 |
+
otherwise permitted by the Creative Commons policies published at
|
| 386 |
+
creativecommons.org/policies, Creative Commons does not authorize the
|
| 387 |
+
use of the trademark "Creative Commons" or any other trademark or logo
|
| 388 |
+
of Creative Commons without its prior written consent including,
|
| 389 |
+
without limitation, in connection with any unauthorized modifications
|
| 390 |
+
to any of its public licenses or any other arrangements,
|
| 391 |
+
understandings, or agreements concerning use of licensed material. For
|
| 392 |
+
the avoidance of doubt, this paragraph does not form part of the
|
| 393 |
+
public licenses.
|
| 394 |
+
|
| 395 |
+
Creative Commons may be contacted at creativecommons.org.
|
| 396 |
+
|
README.md
ADDED
|
@@ -0,0 +1,568 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: cc-by-4.0
|
| 3 |
+
language:
|
| 4 |
+
- zh
|
| 5 |
+
pretty_name: China Administrative Division Codes and Changes, County Level and Above (2012–2025)
|
| 6 |
+
tags:
|
| 7 |
+
- china
|
| 8 |
+
- administrative-divisions
|
| 9 |
+
- geography
|
| 10 |
+
- gazetteer
|
| 11 |
+
- geocoding
|
| 12 |
+
- entity-linking
|
| 13 |
+
- official-statistics
|
| 14 |
+
- provenance
|
| 15 |
+
size_categories:
|
| 16 |
+
- 10K<n<100K
|
| 17 |
+
configs:
|
| 18 |
+
- config_name: years
|
| 19 |
+
data_files:
|
| 20 |
+
- split: train
|
| 21 |
+
path: data/years.csv
|
| 22 |
+
default: true
|
| 23 |
+
- config_name: changes
|
| 24 |
+
data_files:
|
| 25 |
+
- split: train
|
| 26 |
+
path: data/changes.csv
|
| 27 |
+
- config_name: corrections
|
| 28 |
+
data_files:
|
| 29 |
+
- split: train
|
| 30 |
+
path: data/corrections_applied.csv
|
| 31 |
+
dataset_info:
|
| 32 |
+
- config_name: years
|
| 33 |
+
features:
|
| 34 |
+
- name: year
|
| 35 |
+
dtype: int16
|
| 36 |
+
- name: code
|
| 37 |
+
dtype: string
|
| 38 |
+
- name: name
|
| 39 |
+
dtype: string
|
| 40 |
+
- name: level
|
| 41 |
+
dtype: string
|
| 42 |
+
- name: parent_code
|
| 43 |
+
dtype: string
|
| 44 |
+
- name: source_url
|
| 45 |
+
dtype: string
|
| 46 |
+
- name: archive_url
|
| 47 |
+
dtype: string
|
| 48 |
+
- name: fetched
|
| 49 |
+
dtype: string
|
| 50 |
+
- name: verification
|
| 51 |
+
dtype: string
|
| 52 |
+
- config_name: changes
|
| 53 |
+
features:
|
| 54 |
+
- name: year
|
| 55 |
+
dtype: int16
|
| 56 |
+
- name: change_type
|
| 57 |
+
dtype: string
|
| 58 |
+
- name: relation
|
| 59 |
+
dtype: string
|
| 60 |
+
- name: partial
|
| 61 |
+
dtype: string
|
| 62 |
+
- name: main
|
| 63 |
+
dtype: string
|
| 64 |
+
- name: old_code
|
| 65 |
+
dtype: string
|
| 66 |
+
- name: old_name
|
| 67 |
+
dtype: string
|
| 68 |
+
- name: new_code
|
| 69 |
+
dtype: string
|
| 70 |
+
- name: new_name
|
| 71 |
+
dtype: string
|
| 72 |
+
- name: code_changed
|
| 73 |
+
dtype: string
|
| 74 |
+
- name: basis
|
| 75 |
+
dtype: string
|
| 76 |
+
- name: notice_year
|
| 77 |
+
dtype: int16
|
| 78 |
+
- name: evidence
|
| 79 |
+
dtype: string
|
| 80 |
+
- name: note
|
| 81 |
+
dtype: string
|
| 82 |
+
- name: source_url
|
| 83 |
+
dtype: string
|
| 84 |
+
- name: table_source_url
|
| 85 |
+
dtype: string
|
| 86 |
+
- name: fetched
|
| 87 |
+
dtype: string
|
| 88 |
+
- config_name: corrections
|
| 89 |
+
features:
|
| 90 |
+
- name: row
|
| 91 |
+
dtype: string
|
| 92 |
+
- name: action
|
| 93 |
+
dtype: string
|
| 94 |
+
- name: field
|
| 95 |
+
dtype: string
|
| 96 |
+
- name: old_value
|
| 97 |
+
dtype: string
|
| 98 |
+
- name: new_value
|
| 99 |
+
dtype: string
|
| 100 |
+
- name: reason
|
| 101 |
+
dtype: string
|
| 102 |
+
- name: evidence
|
| 103 |
+
dtype: string
|
| 104 |
+
---
|
| 105 |
+
|
| 106 |
+
# China Administrative Division Codes and Changes, County Level and Above (2012–2025)
|
| 107 |
+
|
| 108 |
+
# 中国县级以上行政区划代码和变更(2012—2025)
|
| 109 |
+
|
| 110 |
+
Year-end codes and names of every county-level-and-above administrative division in China for 2012–2025, and every change between consecutive years. Every row links to its official source.
|
| 111 |
+
|
| 112 |
+
2012 至 2025 年每年年底的县级以上行政区划代码和名称,以及相邻两年之间的每一次变更。每一行都带官方出处链接。
|
| 113 |
+
|
| 114 |
+
Published by [World Insight Lab](https://huggingface.co/WorldInsightLab). / 由 World Insight Lab 发布。
|
| 115 |
+
|
| 116 |
+
[English](#english) · [中文](#中文)
|
| 117 |
+
|
| 118 |
+
---
|
| 119 |
+
|
| 120 |
+
## English
|
| 121 |
+
|
| 122 |
+
### Summary
|
| 123 |
+
|
| 124 |
+
| Config | File | Content | Rows |
|
| 125 |
+
|---|---|---|---|
|
| 126 |
+
| `years` (default) | `data/years.csv` | Codes and names of all units at the end of each year, 2012–2025 | 45,009 |
|
| 127 |
+
| `changes` | `data/changes.csv` | Changes between consecutive year-end tables, 2013–2025 | 402 |
|
| 128 |
+
| `corrections` | `data/corrections_applied.csv` | Every correction made before release | 521 |
|
| 129 |
+
|
| 130 |
+
- Levels: province, prefecture, county. No townships, sub-districts or villages.
|
| 131 |
+
- About 3,200 rows per year. End of 2025: 34 province-level, 333 prefecture-level and 2,845 county-level units.
|
| 132 |
+
- Each config has a single `train` split. The split name is a convention of the `datasets` library; there is no train/test meaning.
|
| 133 |
+
- A Python library, **geoalign**, ships in this repository. It maps written place names to codes and converts codes between years. See [Use with geoalign](#use-with-geoalign).
|
| 134 |
+
|
| 135 |
+
Rows in `years.csv` per year:
|
| 136 |
+
|
| 137 |
+
| 2012 | 2013 | 2014 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 2021 | 2022 | 2023 | 2024 | 2025 |
|
| 138 |
+
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
| 139 |
+
| 3,219 | 3,220 | 3,222 | 3,219 | 3,220 | 3,219 | 3,218 | 3,213 | 3,209 | 3,208 | 3,208 | 3,209 | 3,213 | 3,212 |
|
| 140 |
+
|
| 141 |
+
Rows in `changes.csv` per year (the year of the table after the change):
|
| 142 |
+
|
| 143 |
+
| 2013 | 2014 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 2021 | 2022 | 2023 | 2024 | 2025 |
|
| 144 |
+
|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
| 145 |
+
| 35 | 70 | 67 | 74 | 27 | 36 | 38 | 22 | 22 | 0 | 3 | 4 | 4 |
|
| 146 |
+
|
| 147 |
+
2022 has no rows: the 2021 and 2022 year-end tables have the same codes, names and parents.
|
| 148 |
+
|
| 149 |
+
### Columns
|
| 150 |
+
|
| 151 |
+
All code columns (`code`, `parent_code`, `old_code`, `new_code`) are 6-digit **strings**. Keep them as strings when you read the CSV files yourself. Empty cells load as `null` / `None`.
|
| 152 |
+
|
| 153 |
+
**`years.csv`**
|
| 154 |
+
|
| 155 |
+
| Column | Meaning |
|
| 156 |
+
|---|---|
|
| 157 |
+
| `year` | Year. The row describes the state at the end of this year |
|
| 158 |
+
| `code` | 6-digit administrative-division code |
|
| 159 |
+
| `name` | Standard name |
|
| 160 |
+
| `level` | `province`, `prefecture` or `county`, determined from the form of the code |
|
| 161 |
+
| `parent_code` | Parent code. A county's parent is its prefecture, or the province if there is no prefecture. Districts and counties of municipalities, and counties directly under a province, have the province as parent. Empty for provinces |
|
| 162 |
+
| `source_url` | Official source link |
|
| 163 |
+
| `archive_url` | Internet Archive copy, when the original link no longer works |
|
| 164 |
+
| `fetched` | Date the source was retrieved |
|
| 165 |
+
| `verification` | Note on the source |
|
| 166 |
+
|
| 167 |
+
**`changes.csv`**
|
| 168 |
+
|
| 169 |
+
| Column | Meaning |
|
| 170 |
+
|---|---|
|
| 171 |
+
| `year` | Year of the table after the change |
|
| 172 |
+
| `change_type` | Type of change (see below) |
|
| 173 |
+
| `relation` | Shape of the whole change: `一对一` (one-to-one), `多对一` (many-to-one), `一对多` (one-to-many), `多对多` (many-to-many). Empty for `新设` (newly established) rows |
|
| 174 |
+
| `partial` | `是` (yes): only part of the old unit went to the new unit |
|
| 175 |
+
| `main` | `是` (yes): the new unit is the main successor of the old unit (whole conversion, merger, renaming). `否` (no): only part of the old unit went to the new unit, or the notice does not say which side is the main successor |
|
| 176 |
+
| `old_code`, `old_name` | Old code and name |
|
| 177 |
+
| `new_code`, `new_name` | New code and name |
|
| 178 |
+
| `code_changed` | Whether the old and new codes differ (`是` / `否`) |
|
| 179 |
+
| `basis` | Basis: `官方变更情况` (the official annual change notice) or `相邻两年代码表比对` (comparison of two consecutive code tables) |
|
| 180 |
+
| `notice_year` | When the basis is the official notice: the year of the 《县级以上行政区划变更情况》 notice |
|
| 181 |
+
| `evidence` | Sentence quoted from the notice (up to 200 characters), verbatim |
|
| 182 |
+
| `note` | Our explanation (e.g. the code table reflects the change later than the notice). Empty in most rows |
|
| 183 |
+
| `source_url` | Notice link |
|
| 184 |
+
| `table_source_url` | Link to the code table of the year after the change |
|
| 185 |
+
| `fetched` | Date the source was retrieved |
|
| 186 |
+
|
| 187 |
+
Change types (`change_type`):
|
| 188 |
+
|
| 189 |
+
| Value | Meaning |
|
| 190 |
+
|---|---|
|
| 191 |
+
| `改名` | Renamed: same unit, new name |
|
| 192 |
+
| `撤县设区` | County, banner or county-level city converted to a city district |
|
| 193 |
+
| `撤县设市` | County or banner converted to a county-level city |
|
| 194 |
+
| `撤区设县` | City district converted to a county |
|
| 195 |
+
| `撤地设市` | Prefecture (地区) or league (盟) converted to a prefecture-level city |
|
| 196 |
+
| `合并` | Merger: several units combined into one, or one unit abolished and wholly absorbed by another |
|
| 197 |
+
| `拆分` | Split: one unit divided among several units, or part of it transferred to another unit |
|
| 198 |
+
| `代码变化` | Same name, new code. Usually because the parent changed (e.g. after 那曲地区 became 那曲市, 尼玛县 changed from 542430 to 540629) |
|
| 199 |
+
| `新设` | Newly established. The notice states the establishment and names no county-level-or-above predecessor. Mostly formed from townships |
|
| 200 |
+
|
| 201 |
+
`changes.csv` contains 402 rows: 121 撤县设区, 70 拆分, 69 代码变化, 54 合并, 52 撤县设市, 17 新设, 9 改名, 8 撤地设市, 2 撤区设县. 401 rows have the official notice as basis, 1 row has the table comparison as basis.
|
| 202 |
+
|
| 203 |
+
**`corrections_applied.csv`**
|
| 204 |
+
|
| 205 |
+
| Column | Meaning |
|
| 206 |
+
|---|---|
|
| 207 |
+
| `row` | Which change row (year, old unit → new unit) |
|
| 208 |
+
| `action` | `改字段` (field changed, 496), `补行` (row added, 20), `删行` (row deleted, 5) |
|
| 209 |
+
| `field` | Field that was changed |
|
| 210 |
+
| `old_value`, `new_value` | Value before and after |
|
| 211 |
+
| `reason` | Reason |
|
| 212 |
+
| `evidence` | Sentence quoted from the notice |
|
| 213 |
+
|
| 214 |
+
### How to read the change table
|
| 215 |
+
|
| 216 |
+
- One merger or split is written as several rows, one row per pair of old unit and new unit.
|
| 217 |
+
- Rows in the same year that share a code belong to the same change, whether the code appears as an old code or a new code. All rows of one change have the same `relation`.
|
| 218 |
+
- `relation` is decided as follows:
|
| 219 |
+
1. Old side: the old codes in the rows. A unit that keeps its code and wholly absorbs another unit has no row of its own but still counts on the old side (e.g. 白下区 merged into 秦淮区 is one row, “白下区 → 秦淮区”, counted as `多对一`).
|
| 220 |
+
2. New side: the new codes in the rows. A unit that only gives away part of its area and keeps its code does not count on the new side unless it also receives another unit in this change (e.g. part of 龙岗区 became 坪山区: `一对一`).
|
| 221 |
+
3. A unit that both gives away part of its area and receives part of another unit counts on both sides (e.g. in 2025, 北碚区 gave part of its area to 两江新区 and received 5 towns from 渝北区; this group is `多对多`).
|
| 222 |
+
4. One old and one new: `一对一`. One new: `多对一`. One old: `一对多`. Otherwise `多对多`.
|
| 223 |
+
- **Which changes are included**: only changes in which at least one county-level-or-above code appears, disappears or changes. For such a change, every pair of old and new units has a row, including partial transfers. Boundary adjustments in which no code changes are not included (e.g. parts of several counties transferred to 图木舒克市).
|
| 224 |
+
- To follow a unit forward through a split, use the row with `main = 是`. If no row has `main = 是`, the notice names no main successor, and there is no single destination.
|
| 225 |
+
|
| 226 |
+
Example: the 2014 notice abolished 石家庄市桥东区 (130103) and divided its area between 长安区 (130102) and 桥西区 (130104). The change table has two `拆分` rows with `year` 2015 (the code table) and `notice_year` 2014. Both rows have `main = 否`, so there is no single successor.
|
| 227 |
+
|
| 228 |
+
### Sources
|
| 229 |
+
|
| 230 |
+
| Years | Source |
|
| 231 |
+
|---|---|
|
| 232 |
+
| 2012, 2013, 2014 | Original pages on the Ministry of Civil Affairs (MCA, 民政部) website. The original links no longer work; `archive_url` points to the Internet Archive copy |
|
| 233 |
+
| 2015–2024 | Original pages on the MCA website |
|
| 234 |
+
| 2025 | Administrative-division data of the MCA National Geographic Names Information Database (国家地名信息库). Two units established in 2026 were removed; see [Known limitations](#known-limitations) |
|
| 235 |
+
| Changes | MCA annual notices 《县级以上行政区划变更情况》 (`http://xzqh.mca.gov.cn/description?dcpid=<year>`; the pages are GBK-encoded) |
|
| 236 |
+
|
| 237 |
+
Every row carries its source link and retrieval date.
|
| 238 |
+
|
| 239 |
+
**Official pages are recorded as published, including their typos.** Example: the 2015 notice abolished 马尔康县 and established 马尔康**市**, but the official 2015 code table wrote 513201 as “马尔康**区**”; the 2016 table corrected it to “马尔康市”. `years.csv` records “马尔康区” for 2015, and `changes.csv` has a 2016 `改名` row for the correction.
|
| 240 |
+
|
| 241 |
+
### How the data was checked
|
| 242 |
+
|
| 243 |
+
1. Every change row for 2013–2025 was read against that year's official notice. Each correction is listed in `corrections_applied.csv` with the row, field, old value, new value, reason and quoted sentence: 79 rows originally derived from table comparison were found in the notices and re-based on them; `main`, `change_type`, `partial` and `relation` were corrected where the notice says otherwise; 20 partial transfers named in the notices were added; 5 rows were deleted (duplicates, or events recorded in a later year than they belong to); 12 rows that had said “source unknown” or “destination unknown” were resolved. No row now has an unknown source or destination.
|
| 244 |
+
2. A program checked that every `evidence` sentence occurs verbatim in the full notice text. Our own explanations are only in `note`.
|
| 245 |
+
3. Before release the data was reviewed twice independently. The second review compared all 45,009 rows with the 14 official tables retrieved again online and found them identical (for 2025, identical apart from the 2 removed rows); read 67 change rows against the notices and found no discrepancy with the notices in old unit, new unit, type or `partial`; and checked by program that every difference between consecutive tables, 2013–2025, is explained by a change row.
|
| 246 |
+
|
| 247 |
+
### Usage
|
| 248 |
+
|
| 249 |
+
**With `datasets`**
|
| 250 |
+
|
| 251 |
+
```python
|
| 252 |
+
from datasets import load_dataset
|
| 253 |
+
|
| 254 |
+
years = load_dataset("WorldInsightLab/china-admin-divisions", "years", split="train")
|
| 255 |
+
changes = load_dataset("WorldInsightLab/china-admin-divisions", "changes", split="train")
|
| 256 |
+
|
| 257 |
+
print(years.num_rows, changes.num_rows) # 45009 402
|
| 258 |
+
print(years[1])
|
| 259 |
+
# {'year': 2012, 'code': '110101', 'name': '东城区', 'level': 'county', 'parent_code': '110000', ...}
|
| 260 |
+
```
|
| 261 |
+
|
| 262 |
+
**With pandas** (read codes as strings):
|
| 263 |
+
|
| 264 |
+
```python
|
| 265 |
+
import pandas as pd
|
| 266 |
+
|
| 267 |
+
base = "hf://datasets/WorldInsightLab/china-admin-divisions/data/"
|
| 268 |
+
years = pd.read_csv(base + "years.csv", dtype=str, keep_default_na=False)
|
| 269 |
+
changes = pd.read_csv(base + "changes.csv", dtype=str, keep_default_na=False)
|
| 270 |
+
|
| 271 |
+
y2025 = years[years.year == "2025"]
|
| 272 |
+
print(y2025.level.value_counts().to_dict())
|
| 273 |
+
# {'county': 2845, 'prefecture': 333, 'province': 34}
|
| 274 |
+
|
| 275 |
+
print(changes[changes.old_code == "130103"][["year", "change_type", "main", "new_code", "new_name"]])
|
| 276 |
+
# year change_type main new_code new_name
|
| 277 |
+
# 109 2015 拆分 否 130102 长安区
|
| 278 |
+
# 110 2015 拆分 否 130104 桥西区
|
| 279 |
+
```
|
| 280 |
+
|
| 281 |
+
`hf://` paths need `huggingface_hub` installed. You can also download the CSV files and read them locally.
|
| 282 |
+
|
| 283 |
+
### Use with geoalign
|
| 284 |
+
|
| 285 |
+
`geoalign/` in this repository is a small Python library (Apache-2.0, standard library only, Python 3.8+) built on this data. It maps written names to codes, converts codes between years and shows the history of a code. When it is not sure, it gives no code and lists the candidates.
|
| 286 |
+
|
| 287 |
+
Install the wheel from this repository:
|
| 288 |
+
|
| 289 |
+
```
|
| 290 |
+
pip install https://huggingface.co/datasets/WorldInsightLab/china-admin-divisions/resolve/main/geoalign/dist/geoalign-0.1.0-py3-none-any.whl
|
| 291 |
+
```
|
| 292 |
+
|
| 293 |
+
```python
|
| 294 |
+
from geoalign import Gazetteer
|
| 295 |
+
g = Gazetteer()
|
| 296 |
+
|
| 297 |
+
g.align("密云县").code # '110118' (密云区, the latest code)
|
| 298 |
+
g.align("密云县", year=2013).code # '110228'
|
| 299 |
+
g.align("朝阳区", parent="长春市").code # '220104'
|
| 300 |
+
g.align("朝阳区").code # None: two units share this name; see .candidates
|
| 301 |
+
g.to_year("130103", 2016).codes # ['130102', '130104'] (split, exact=False)
|
| 302 |
+
```
|
| 303 |
+
|
| 304 |
+
Full documentation, the public benchmark and its results: [`geoalign/README.md`](geoalign/README.md). The library covers county level and above only; do not pass township names.
|
| 305 |
+
|
| 306 |
+
### Known limitations
|
| 307 |
+
|
| 308 |
+
1. **County level and above only.** No townships, sub-districts or villages. Do not use the data or the library to code township names.
|
| 309 |
+
2. **No years before 2012.**
|
| 310 |
+
3. **The 2025 table is the year-end state, based on the 2026 notice.** The National Geographic Names Information Database returns the version current on the day of retrieval. It included 岑岭县 (653132, announced 2026-03-26) and 草湖市 (659013, announced 2026-04-17). At retrieval time the 2026 notice 《2026 年县级以上行政区划变更情况》 had only these 2 entries. We removed these 2 rows to get the state at the end of 2025, so every year uses the same year-end convention. If the database contains a 2026 change that the notice does not yet list (e.g. a renaming only), we cannot detect it.
|
| 311 |
+
4. **Code tables can lag behind notices.** Some changes appear in the notice for one year but in the code table one or more years later. Example: 三沙市西沙区 and 南沙区 were established in 2020 and first appear in the 2024 table; 保定市南市区 was merged into 莲池区 in 2015, and 130604 was removed from the table only in 2017. In `changes.csv`, `year` follows the code table and `notice_year` follows the notice. Lagging rows are explained in `note`. One event is recorded once, in the year the code table reflects it. As a result, the 2015 and 2016 tables contain both 南市区 and 莲池区, and converting 2015's 莲池区 back to 2014 gives only 北市区.
|
| 312 |
+
5. **双湖县** was established in 2012 and is already in the 2012 table as 542431. After 那曲地区 became a city in 2017, its code changed to 540630.
|
| 313 |
+
6. **Hong Kong, Macao, Taiwan**: 台湾省 is listed as 710000, as in the MCA tables of each year. The National Geographic Names Information Database gives its code as “资料暂缺” (data not available).
|
| 314 |
+
7. **Official typos are kept** (see [Sources](#sources)).
|
| 315 |
+
|
| 316 |
+
### License and attribution
|
| 317 |
+
|
| 318 |
+
1. The compilation, organization and annotations in `data/` (the change types, relations and successor annotations of the change table, and the correction records) are released under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). See `LICENSE`.
|
| 319 |
+
2. The administrative-division codes, names and notice texts come from documents published by the Ministry of Civil Affairs of the People's Republic of China. See [Sources](#sources) and the source link on every row. CC BY 4.0 does not cover this official content itself.
|
| 320 |
+
3. The `geoalign/` library is under Apache-2.0; third-party notices are in `geoalign/NOTICE`.
|
| 321 |
+
|
| 322 |
+
Suggested attribution: “China Administrative Division Codes and Changes (2012–2025), World Insight Lab, CC BY 4.0. Underlying data: Ministry of Civil Affairs of the People's Republic of China.”
|
| 323 |
+
|
| 324 |
+
### Versions
|
| 325 |
+
|
| 326 |
+
| Version | Date | Changes |
|
| 327 |
+
|---|---|---|
|
| 328 |
+
| 1.0 | 2026-11 | First release. Year-end tables 2012–2025 (45,009 rows), changes 2013–2025 (402 rows), 521 correction records; geoalign 0.1.0. Sources retrieved 2026-11-18 |
|
| 329 |
+
|
| 330 |
+
### Citation
|
| 331 |
+
|
| 332 |
+
```bibtex
|
| 333 |
+
@misc{worldinsightlab_china_admin_divisions_2026,
|
| 334 |
+
author = {{World Insight Lab}},
|
| 335 |
+
title = {China Administrative Division Codes and Changes, County Level and Above (2012--2025)},
|
| 336 |
+
year = {2026},
|
| 337 |
+
version = {1.0},
|
| 338 |
+
publisher = {Hugging Face},
|
| 339 |
+
howpublished = {\url{https://huggingface.co/datasets/WorldInsightLab/china-admin-divisions}},
|
| 340 |
+
note = {Underlying data: Ministry of Civil Affairs of the People's Republic of China}
|
| 341 |
+
}
|
| 342 |
+
```
|
| 343 |
+
|
| 344 |
+
---
|
| 345 |
+
|
| 346 |
+
## 中文
|
| 347 |
+
|
| 348 |
+
### 概况
|
| 349 |
+
|
| 350 |
+
| 配置 | 文件 | 内容 | 行数 |
|
| 351 |
+
|---|---|---|---|
|
| 352 |
+
| `years`(默认) | `data/years.csv` | 2012 至 2025 年,每年年底的县级以上代码和名称 | 45,009 |
|
| 353 |
+
| `changes` | `data/changes.csv` | 2013 至 2025 年,相邻两年代码表之间的变更 | 402 |
|
| 354 |
+
| `corrections` | `data/corrections_applied.csv` | 发布前做的全部改正 | 521 |
|
| 355 |
+
|
| 356 |
+
- 层级:省级、地级、县级。没有乡镇、街道、村。
|
| 357 |
+
- 每年约 3,200 行。2025 年底:省级 34 个、地级 333 个、县级 2,845 个。
|
| 358 |
+
- 每个配置只有一个 `train` 划分。这是 `datasets` 库的惯例,没有训练集、测试集的意思。
|
| 359 |
+
- 仓库里带一个 Python 工具库 **geoalign**:把地名写法变成代码,在年份之间换算代码。见[配合 geoalign 使用](#配合-geoalign-使用)。
|
| 360 |
+
|
| 361 |
+
`years.csv` 每年的行数:
|
| 362 |
+
|
| 363 |
+
| 2012 | 2013 | 2014 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 2021 | 2022 | 2023 | 2024 | 2025 |
|
| 364 |
+
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
| 365 |
+
| 3,219 | 3,220 | 3,222 | 3,219 | 3,220 | 3,219 | 3,218 | 3,213 | 3,209 | 3,208 | 3,208 | 3,209 | 3,213 | 3,212 |
|
| 366 |
+
|
| 367 |
+
`changes.csv` 每年的行数(按变更后那一年的表计):
|
| 368 |
+
|
| 369 |
+
| 2013 | 2014 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 2021 | 2022 | 2023 | 2024 | 2025 |
|
| 370 |
+
|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
| 371 |
+
| 35 | 70 | 67 | 74 | 27 | 36 | 38 | 22 | 22 | 0 | 3 | 4 | 4 |
|
| 372 |
+
|
| 373 |
+
2022 年没有行:2021 年底和 2022 年底的表,代码、名称、上级完全相同。
|
| 374 |
+
|
| 375 |
+
### 各列的意思
|
| 376 |
+
|
| 377 |
+
所有代码列(`code`、`parent_code`、`old_code`、`new_code`)都是 6 位的**字符串**。自己读 CSV 时请按字符串读。空单元格读出来是 `null` / `None`。
|
| 378 |
+
|
| 379 |
+
**`years.csv`**
|
| 380 |
+
|
| 381 |
+
| 列 | 意思 |
|
| 382 |
+
|---|---|
|
| 383 |
+
| `year` | 年份。表示这一年年底的状态 |
|
| 384 |
+
| `code` | 6 位行政区划代码 |
|
| 385 |
+
| `name` | 标准名称 |
|
| 386 |
+
| `level` | `province`(省级)、`prefecture`(地级)、`county`(县级)。按代码的形式判断 |
|
| 387 |
+
| `parent_code` | 上级代码。县的上级是地级,没有地级时是省。直辖市的区县、省直辖县的上级是省。省级为空 |
|
| 388 |
+
| `source_url` | 官方出处链接 |
|
| 389 |
+
| `archive_url` | 原链接失效时,互联网档案馆的存档副本链接 |
|
| 390 |
+
| `fetched` | 获取日期 |
|
| 391 |
+
| `verification` | 出处的说明 |
|
| 392 |
+
|
| 393 |
+
**`changes.csv`**
|
| 394 |
+
|
| 395 |
+
| 列 | 意思 |
|
| 396 |
+
|---|---|
|
| 397 |
+
| `year` | 变更后的表的年份 |
|
| 398 |
+
| `change_type` | 变更类型,见下表 |
|
| 399 |
+
| `relation` | 这一次变更整体的形状:`一对一`、`多对一`、`一对多`、`多对多`。新设的行为空 |
|
| 400 |
+
| `partial` | `是`:旧单位只有一部分划给新单位 |
|
| 401 |
+
| `main` | `是`:新单位是旧单位的主要承继(整体改设、合并、改名)。`否`:只是旧单位的一部分划给了新单位,或者公告没有说哪一方是主要承继 |
|
| 402 |
+
| `old_code`、`old_name` | 旧代码、旧名称 |
|
| 403 |
+
| `new_code`、`new_name` | 新代码、新名称 |
|
| 404 |
+
| `code_changed` | 新旧代码是否不同(`是` / `否`) |
|
| 405 |
+
| `basis` | 依据:`官方变更情况` 或 `相邻两年代码表比对` |
|
| 406 |
+
| `notice_year` | 依据是官方变更情况时,是哪一年的《县级以上行政区划变更情况》 |
|
| 407 |
+
| `evidence` | 公告原句(最多 200 字),原样照录 |
|
| 408 |
+
| `note` | 我们的说明(例:代码表比公告晚)。多数行是空的 |
|
| 409 |
+
| `source_url` | 公告链接 |
|
| 410 |
+
| `table_source_url` | 变更后那一年代码表的链接 |
|
| 411 |
+
| `fetched` | 获取日期 |
|
| 412 |
+
|
| 413 |
+
变更类型:
|
| 414 |
+
|
| 415 |
+
| 类型 | 意思 |
|
| 416 |
+
|---|---|
|
| 417 |
+
| 改名 | 同一个单位换了名称 |
|
| 418 |
+
| 撤县设区 | 县、旗、县级市改为市辖区 |
|
| 419 |
+
| 撤县设市 | 县、旗改为县级市 |
|
| 420 |
+
| 撤区设县 | 市辖区改为县 |
|
| 421 |
+
| 撤地设市 | 地区、盟改为地级市 |
|
| 422 |
+
| 合并 | 多个单位合成一个,或一个单位撤销后整个并入另一个 |
|
| 423 |
+
| 拆分 | 一个单位分给多个单位,或一部分划给别的单位 |
|
| 424 |
+
| 代码变化 | 名称不变,代码变了。多数是上级变了(例:那曲地区改为那曲市以后,尼玛县 542430 改为 540629) |
|
| 425 |
+
| 新设 | 公告写明设立,没有说从哪个县级以上单位来。多数由乡镇设立 |
|
| 426 |
+
|
| 427 |
+
`changes.csv` 共 402 行:撤县设区 121、拆分 70、代码变化 69、合并 54、撤县设市 52、新设 17、改名 9、撤地设市 8、撤区设县 2。依据是官方变更情况的 401 行,相邻两年代码表比对的 1 行。
|
| 428 |
+
|
| 429 |
+
**`corrections_applied.csv`**
|
| 430 |
+
|
| 431 |
+
| 列 | 意思 |
|
| 432 |
+
|---|---|
|
| 433 |
+
| `row` | 哪一行变更(年份、旧单位 → 新单位) |
|
| 434 |
+
| `action` | `改字段`(496 条)、`补行`(20 条)、`删行`(5 条) |
|
| 435 |
+
| `field` | 改的字段 |
|
| 436 |
+
| `old_value`、`new_value` | 原来的值、改后的值 |
|
| 437 |
+
| `reason` | 理由 |
|
| 438 |
+
| `evidence` | 公告原句 |
|
| 439 |
+
|
| 440 |
+
### 变更表怎么读
|
| 441 |
+
|
| 442 |
+
- 一次合并或拆分写成多行,每对旧单位和新单位一行。
|
| 443 |
+
- 同一年里共用一个代码的行算同一次变更,不管这个代码在行里是旧代码还是新代码。同一次变更的各行写同一个 `relation`。
|
| 444 |
+
- `relation` 的写法:
|
| 445 |
+
1. 旧的一方:行里的旧代码。保留原代码、整体接收了别的单位的一方不写行,但也算旧的一方(例:白下区并入秦淮区,只有“白下区→秦淮区”一行,算 `多对一`)。
|
| 446 |
+
2. 新的一方:行里的新代码。只划出一部分、自己代码不变的单位,如果在这次变更里没有接收别的单位,不算到新的一方(例:龙岗区划出一部分设立坪山区,写 `一对一`)。
|
| 447 |
+
3. 一个单位既划出一部分、又接收了别的单位的一部分时,两边都算(例:2025 年北碚区划给两江新区一部分,又接收渝北区的 5 个镇,这一组写 `多对多`)。
|
| 448 |
+
4. 旧的一方、新的一方各 1 个是 `一对一`。新的一方 1 个是 `多对一`。旧的一方 1 个是 `一对多`。其他是 `多对多`。
|
| 449 |
+
- **哪些变更进表**:只收至少有一个县级以上代码出现、消失或改变的变更。它的每一对旧单位、新单位都写一行,包括只划了一部分的。只调整边界、所有代码都没变的变更不收(例:几个县的部分区域划给图木舒克市)。
|
| 450 |
+
- 沿拆分往后找一个单位的去向时,用 `main = 是` 的行。没有 `main = 是` 的行时,公告没有说主要承继,去向不唯一。
|
| 451 |
+
|
| 452 |
+
例:2014 年的公告撤销石家庄市桥东区(130103),区域分给长安区(130102)和桥西区(130104)。变更表里有两行 `拆分`,`year` 是 2015(按代码表),`notice_year` 是 2014。两行都是 `main = 否`,去向不唯一。
|
| 453 |
+
|
| 454 |
+
### 出处
|
| 455 |
+
|
| 456 |
+
| 年份 | 来源 |
|
| 457 |
+
|---|---|
|
| 458 |
+
| 2012、2013、2014 | 民政部官网原页。原链接已失效,`archive_url` 是互联网档案馆的存档副本 |
|
| 459 |
+
| 2015 至 2024 | 民政部官网原页 |
|
| 460 |
+
| 2025 | 民政部国家地名信息库的行政区划数据。去掉了 2026 年才设立的 2 个单位,见[已知的限制](#已知的限制) |
|
| 461 |
+
| 变更 | 民政部《县级以上行政区划变更情况》(`http://xzqh.mca.gov.cn/description?dcpid=<年份>`,网页用 GBK 编码) |
|
| 462 |
+
|
| 463 |
+
每一行都带出处链接和获取日期。
|
| 464 |
+
|
| 465 |
+
**照录官方页**:代码和名称照官方页原样记录,官方页上的笔误也照录,不改。例:2015 年公告撤销马尔康县、设立马尔康**市**,但 2015 年的官方代码表把 513201 写成“马尔康**区**”,2016 年的表才改成“马尔康市”。`years.csv` 的 2015 年照录“马尔康区”,`changes.csv` 里有一行 2016 年的“改名”记录这次更正。
|
| 466 |
+
|
| 467 |
+
### 怎么核对的
|
| 468 |
+
|
| 469 |
+
1. 2013 至 2025 年的全部变更行,对照每一年的公告逐条读过。每一处改正都列在 `corrections_applied.csv`:哪一行、哪个字段、原来的值、改后的值、理由、公告原句。原来按代码表比对得出、公告里其实有的 79 行,改为以公告为依据;`main`、变更类型、`partial`、`relation` 按公告改正;补 20 行公告写了、原来没有记的部分划转;删 5 行(重复记录,或者把以前年份的事记到了后面的年份);原来 12 行“来源未查明”“去向未查明”,全部按公告改正。现在没有说不清来源或去向的行。
|
| 470 |
+
2. `evidence` 里的公告原句都由程序在公告全文里原样核对过。我们的说明只写在 `note` 里。
|
| 471 |
+
3. 发布前做过两轮独立复查。第二轮:把 45,009 行和重新联网取回的 14 张官方表逐条比对,结果一致(2025 年除去掉的 2 行外完全一致);对照公告读了 67 行变更,旧单位、新单位、类型、`partial` 都和公告一致;用程序检查 2013 至 2025 年相邻两年代码表的每一处差异都有变更行解释。
|
| 472 |
+
|
| 473 |
+
### 怎么用
|
| 474 |
+
|
| 475 |
+
**用 `datasets`**
|
| 476 |
+
|
| 477 |
+
```python
|
| 478 |
+
from datasets import load_dataset
|
| 479 |
+
|
| 480 |
+
years = load_dataset("WorldInsightLab/china-admin-divisions", "years", split="train")
|
| 481 |
+
changes = load_dataset("WorldInsightLab/china-admin-divisions", "changes", split="train")
|
| 482 |
+
|
| 483 |
+
print(years.num_rows, changes.num_rows) # 45009 402
|
| 484 |
+
print(years[1])
|
| 485 |
+
# {'year': 2012, 'code': '110101', 'name': '东城区', 'level': 'county', 'parent_code': '110000', ...}
|
| 486 |
+
```
|
| 487 |
+
|
| 488 |
+
**用 pandas**(代码按字符串读):
|
| 489 |
+
|
| 490 |
+
```python
|
| 491 |
+
import pandas as pd
|
| 492 |
+
|
| 493 |
+
base = "hf://datasets/WorldInsightLab/china-admin-divisions/data/"
|
| 494 |
+
years = pd.read_csv(base + "years.csv", dtype=str, keep_default_na=False)
|
| 495 |
+
changes = pd.read_csv(base + "changes.csv", dtype=str, keep_default_na=False)
|
| 496 |
+
|
| 497 |
+
y2025 = years[years.year == "2025"]
|
| 498 |
+
print(y2025.level.value_counts().to_dict())
|
| 499 |
+
# {'county': 2845, 'prefecture': 333, 'province': 34}
|
| 500 |
+
|
| 501 |
+
print(changes[changes.old_code == "130103"][["year", "change_type", "main", "new_code", "new_name"]])
|
| 502 |
+
# year change_type main new_code new_name
|
| 503 |
+
# 109 2015 拆分 否 130102 长安区
|
| 504 |
+
# 110 2015 拆分 否 130104 桥西区
|
| 505 |
+
```
|
| 506 |
+
|
| 507 |
+
`hf://` 路径要装 `huggingface_hub`。也可以把 CSV 文件下载到本地再读。
|
| 508 |
+
|
| 509 |
+
### 配合 geoalign 使用
|
| 510 |
+
|
| 511 |
+
仓库里的 `geoalign/` 是基于这份数据的 Python 工具库(Apache-2.0,只用标准库,Python 3.8 以上)。它把地名写法变成代码,在年份之间换算代码,查一个代码的沿革。没有把握时不给代码,给全部候选。
|
| 512 |
+
|
| 513 |
+
从本仓库安装 wheel:
|
| 514 |
+
|
| 515 |
+
```
|
| 516 |
+
pip install https://huggingface.co/datasets/WorldInsightLab/china-admin-divisions/resolve/main/geoalign/dist/geoalign-0.1.0-py3-none-any.whl
|
| 517 |
+
```
|
| 518 |
+
|
| 519 |
+
```python
|
| 520 |
+
from geoalign import Gazetteer
|
| 521 |
+
g = Gazetteer()
|
| 522 |
+
|
| 523 |
+
g.align("密云县").code # '110118'(密云区,最新的代码)
|
| 524 |
+
g.align("密云县", year=2013).code # '110228'
|
| 525 |
+
g.align("朝阳区", parent="长春市").code # '220104'
|
| 526 |
+
g.align("朝阳区").code # None:有两个朝阳区,见 .candidates
|
| 527 |
+
g.to_year("130103", 2016).codes # ['130102', '130104'](拆分,exact=False)
|
| 528 |
+
```
|
| 529 |
+
|
| 530 |
+
完整说明、公开测试题和成绩见 [`geoalign/README.md`](geoalign/README.md)。工具库只管县级以上,不要把乡镇名交给它。
|
| 531 |
+
|
| 532 |
+
### 已知的限制
|
| 533 |
+
|
| 534 |
+
1. **只到县级以上**。没有乡镇、街道、村。不要用这份数据或工具库给乡镇名配代码。
|
| 535 |
+
2. **没有 2012 年以前的数据**。
|
| 536 |
+
3. **2025 年是年底的状态,依据是 2026 年的公告**。国家地名信息库给的是取数当天的现行版,里面有 2026 年公告设立的岑岭县(653132,2026-03-26 公告)和草湖市(659013,2026-04-17 公告)。取数时《2026 年县级以上行政区划变更情况》只有这 2 条。我们去掉这 2 行,得到 2025 年底的状态。这样每一年都按同一个口径(年底)。如果国家地名信息库里有公告还没写的 2026 年变化(例:只改了名称),我们查不出来。
|
| 537 |
+
4. **代码表比公告晚**。有的变更在公告里是一年,代码表晚一年或几年才反映。例:三沙市西沙区、南沙区 2020 年设立,2024 年的表才有。保定市南市区 2015 年并入莲池区,2017 年的表才去掉 130604。变更表的 `year` 按代码表记,`notice_year` 按公告记。代码表晚的行在 `note` 里写了说明。同一件事只记一行,记在代码表反映它的那一年。所以 2015、2016 年的代码表里南市区和莲池区同时存在,把 2015 年的莲池区换回 2014 年时,只得到北市区。
|
| 538 |
+
5. **双湖县**:2012 年设立。2012 年的表就有 542431 双湖县。2017 年那曲撤地设市以后,代码改为 540630。
|
| 539 |
+
6. **港澳台**:台湾省按历年民政部表写 710000。国家地名信息库把台湾省的代码写成“资料暂缺”。
|
| 540 |
+
7. **官方笔误照录**(见[出处](#出处))。
|
| 541 |
+
|
| 542 |
+
### 许可和出处声明
|
| 543 |
+
|
| 544 |
+
1. `data/` 里的编排、整理和标注(变更表的类型、关系、承继标注,改正记录)按 [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/deed.zh-hans) 许可发布,见 `LICENSE`。
|
| 545 |
+
2. 行政区划代码、名称和公告原文来自中华人民共和国民政部公开发布的文件,见[出处](#出处)和每一行的出处链接。CC BY 4.0 不覆盖这些官方内容本身。
|
| 546 |
+
3. `geoalign/` 工具库按 Apache-2.0 许可发布,第三方声明见 `geoalign/NOTICE`。
|
| 547 |
+
|
| 548 |
+
建议的署名写法:“中国县级以上行政区划代码和变更(2012—2025),World Insight Lab,CC BY 4.0。底层数据:中华人民共和国民政部。”
|
| 549 |
+
|
| 550 |
+
### 版本和更新记录
|
| 551 |
+
|
| 552 |
+
| 版本 | 日期 | 内容 |
|
| 553 |
+
|---|---|---|
|
| 554 |
+
| 1.0 | 2026-11 | 第一版。2012 至 2025 年年底的代码表(45,009 行),2013 至 2025 年的变更(402 行),改正记录 521 条;geoalign 0.1.0。出处获取日期 2026-11-18 |
|
| 555 |
+
|
| 556 |
+
### 引用
|
| 557 |
+
|
| 558 |
+
```bibtex
|
| 559 |
+
@misc{worldinsightlab_china_admin_divisions_2026,
|
| 560 |
+
author = {{World Insight Lab}},
|
| 561 |
+
title = {China Administrative Division Codes and Changes, County Level and Above (2012--2025)},
|
| 562 |
+
year = {2026},
|
| 563 |
+
version = {1.0},
|
| 564 |
+
publisher = {Hugging Face},
|
| 565 |
+
howpublished = {\url{https://huggingface.co/datasets/WorldInsightLab/china-admin-divisions}},
|
| 566 |
+
note = {Underlying data: Ministry of Civil Affairs of the People's Republic of China}
|
| 567 |
+
}
|
| 568 |
+
```
|
data/changes.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/corrections_applied.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/years.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
geoalign/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Apache License
|
| 3 |
+
Version 2.0, January 2004
|
| 4 |
+
http://www.apache.org/licenses/
|
| 5 |
+
|
| 6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
| 178 |
+
|
| 179 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 180 |
+
|
| 181 |
+
To apply the Apache License to your work, attach the following
|
| 182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 183 |
+
replaced with your own identifying information. (Don't include
|
| 184 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 185 |
+
comment syntax for the file format. We also recommend that a
|
| 186 |
+
file or class name and description of purpose be included on the
|
| 187 |
+
same "printed page" as the copyright notice for easier
|
| 188 |
+
identification within third-party archives.
|
| 189 |
+
|
| 190 |
+
Copyright [yyyy] [name of copyright owner]
|
| 191 |
+
|
| 192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 193 |
+
you may not use this file except in compliance with the License.
|
| 194 |
+
You may obtain a copy of the License at
|
| 195 |
+
|
| 196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 197 |
+
|
| 198 |
+
Unless required by applicable law or agreed to in writing, software
|
| 199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 201 |
+
See the License for the specific language governing permissions and
|
| 202 |
+
limitations under the License.
|
geoalign/NOTICE
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
geoalign
|
| 2 |
+
本包的代码按 Apache-2.0 许可发布(见 LICENSE)。本包带的数据文件里有第三方的内容,说明如下。
|
| 3 |
+
|
| 4 |
+
1. geoalign/data/confusion.json 里的拼音("pinyin"、"pinyin_main" 两部分)
|
| 5 |
+
由 pypinyin 0.55.0 生成。pypinyin 的单字拼音数据来自 pinyin-data 项目。两者都按 MIT 许可发布,版权声明和许可全文如下。
|
| 6 |
+
|
| 7 |
+
----- pypinyin(https://github.com/mozillazg/python-pinyin) -----
|
| 8 |
+
The MIT License (MIT)
|
| 9 |
+
|
| 10 |
+
Copyright (c) 2016 mozillazg, 闲耘 <hotoo.cn@gmail.com>
|
| 11 |
+
|
| 12 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
| 13 |
+
this software and associated documentation files (the "Software"), to deal in
|
| 14 |
+
the Software without restriction, including without limitation the rights to
|
| 15 |
+
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
| 16 |
+
the Software, and to permit persons to whom the Software is furnished to do so,
|
| 17 |
+
subject to the following conditions:
|
| 18 |
+
|
| 19 |
+
The above copyright notice and this permission notice shall be included in all
|
| 20 |
+
copies or substantial portions of the Software.
|
| 21 |
+
|
| 22 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 23 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
| 24 |
+
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
| 25 |
+
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
| 26 |
+
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
| 27 |
+
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
| 28 |
+
|
| 29 |
+
----- pinyin-data(https://github.com/mozillazg/pinyin-data) -----
|
| 30 |
+
The MIT License (MIT)
|
| 31 |
+
|
| 32 |
+
Copyright (c) 2016 mozillazg
|
| 33 |
+
|
| 34 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 35 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 36 |
+
in the Software without restriction, including without limitation the rights
|
| 37 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 38 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 39 |
+
furnished to do so, subject to the following conditions:
|
| 40 |
+
|
| 41 |
+
The above copyright notice and this permission notice shall be included in all
|
| 42 |
+
copies or substantial portions of the Software.
|
| 43 |
+
|
| 44 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 45 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 46 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 47 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 48 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 49 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 50 |
+
SOFTWARE.
|
| 51 |
+
|
| 52 |
+
2. geoalign/data/confusion.json 里的形近字("shape" 部分)
|
| 53 |
+
用 Noto Sans CJK SC 字体把字画成图、比较图的相似度得到(方法见 tools/build_confusion.py)。
|
| 54 |
+
本包不带字体文件,只带计算出的字对。Noto Sans CJK 按 SIL Open Font License 1.1 发布(https://github.com/notofonts/noto-cjk)。
|
| 55 |
+
|
| 56 |
+
3. geoalign/data/ 里的行政区划代码、名称和变更来自民政部公开发布的文件。出处和许可见数据集的说明。
|
geoalign/README.md
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# geoalign
|
| 2 |
+
|
| 3 |
+
Map Chinese administrative-division names (county level and above) to official codes, and convert codes between years 2012–2025.
|
| 4 |
+
|
| 5 |
+
把中国县级以上行政区划的名称写法对到官方代码,并在 2012 至 2025 年之间换算代码。
|
| 6 |
+
|
| 7 |
+
- Data / 数据: [WorldInsightLab/china-admin-divisions](https://huggingface.co/datasets/WorldInsightLab/china-admin-divisions)
|
| 8 |
+
- License / 许可: code Apache-2.0 (`LICENSE`); third-party notices in `NOTICE` / 代码 Apache-2.0,第三方声明见 `NOTICE`
|
| 9 |
+
- Version / 版本: 0.1.0
|
| 10 |
+
|
| 11 |
+
[English](#english) · [中文](#中文)
|
| 12 |
+
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
## English
|
| 16 |
+
|
| 17 |
+
### What it does
|
| 18 |
+
|
| 19 |
+
1. Turns a written place name into an administrative-division code. You can give a year and a parent name.
|
| 20 |
+
2. Converts a code from one year to another. For splits and mergers it returns every destination.
|
| 21 |
+
3. Shows the history of a code.
|
| 22 |
+
|
| 23 |
+
When the library is not sure, it returns no code and lists all candidates instead.
|
| 24 |
+
|
| 25 |
+
### Install
|
| 26 |
+
|
| 27 |
+
From the wheel in the dataset repository:
|
| 28 |
+
|
| 29 |
+
```
|
| 30 |
+
pip install https://huggingface.co/datasets/WorldInsightLab/china-admin-divisions/resolve/main/geoalign/dist/geoalign-0.1.0-py3-none-any.whl
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
From source (run in the `geoalign/` directory, where `pyproject.toml` is):
|
| 34 |
+
|
| 35 |
+
```
|
| 36 |
+
pip install .
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
- Lookup and the typo rules use only the Python standard library (Python 3.8+). No GPU.
|
| 40 |
+
- 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.
|
| 41 |
+
|
| 42 |
+
### Scope
|
| 43 |
+
|
| 44 |
+
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.
|
| 45 |
+
2. If the year is earlier than 2012, the library gives no code, and `note` says the data starts in 2012.
|
| 46 |
+
3. If the year is later than 2025, the 2025 table is used.
|
| 47 |
+
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.
|
| 48 |
+
|
| 49 |
+
### Usage
|
| 50 |
+
|
| 51 |
+
The outputs below were produced by the wheel above, installed in a clean virtual environment.
|
| 52 |
+
|
| 53 |
+
```python
|
| 54 |
+
from geoalign import Gazetteer
|
| 55 |
+
g = Gazetteer()
|
| 56 |
+
|
| 57 |
+
m = g.align("密云县") # no year: map to the latest code
|
| 58 |
+
(m.code, m.name, m.confidence, m.method, m.year)
|
| 59 |
+
# ('110118', '密云区', 'medium', 'history', 2025)
|
| 60 |
+
|
| 61 |
+
g.align("密云县", year=2013).code # '110228' — still 密云县 at the end of 2013
|
| 62 |
+
g.align("朝阳区", parent="长春市").code # '220104'
|
| 63 |
+
|
| 64 |
+
m = g.align("朝阳区") # duplicate name, no parent
|
| 65 |
+
(m.code, m.best, m.confidence, m.method)
|
| 66 |
+
# (None, '110105', 'low', 'exact') # not sure: no code
|
| 67 |
+
[(c.code, c.name, c.parent_name) for c in m.candidates]
|
| 68 |
+
# [('110105', '朝阳区', '北京市'), ('220104', '朝阳区', '吉林省长春市')]
|
| 69 |
+
|
| 70 |
+
m = g.align("天水市麦积区") # parent and name written together
|
| 71 |
+
(m.code, m.name, m.confidence, m.method)
|
| 72 |
+
# ('620503', '麦积区', 'medium', 'split')
|
| 73 |
+
|
| 74 |
+
m = g.align("密云县", year=1990) # earlier than 2012
|
| 75 |
+
(m.code, m.confidence)
|
| 76 |
+
# (None, 'low')
|
| 77 |
+
|
| 78 |
+
g.to_year("110228", 2025)
|
| 79 |
+
# YearResult(codes=['110118'], names=['密云区'], exact=True,
|
| 80 |
+
# steps=['2014→2015:110228 密云县 → 110118 密云区(撤县设区)'])
|
| 81 |
+
|
| 82 |
+
g.to_year("130103", 2016) # 石家庄 桥东区, split in 2014
|
| 83 |
+
# YearResult(codes=['130102', '130104'], names=['长安区', '桥西区'], exact=False,
|
| 84 |
+
# steps=['2014→2015:130103 桥东区 → 130102 长安区(拆分)',
|
| 85 |
+
# '2014→2015:130103 桥东区 → 130104 桥西区(拆分)'])
|
| 86 |
+
|
| 87 |
+
g.history("330103") # 杭州 下城区, merged into 拱墅区 in 2021
|
| 88 |
+
# {'code': '330103', 'names': [{'name': '下城区', 'from': 2012, 'to': 2020}],
|
| 89 |
+
# 'events': [{'year': 2021, 'type': '合并', 'relation': '多对一', 'partial': False,
|
| 90 |
+
# 'old_code': '330103', 'old_name': '下城区', 'new_code': '330105', 'new_name': '拱墅区',
|
| 91 |
+
# 'basis': '官方变更情况', 'source_url': 'http://xzqh.mca.gov.cn/description?dcpid=2021'}]}
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
Fields returned by `align`:
|
| 95 |
+
|
| 96 |
+
| Field | Meaning |
|
| 97 |
+
|---|---|
|
| 98 |
+
| `code` | The code when the library is sure; otherwise `None` |
|
| 99 |
+
| `best` | The top candidate. Given even when not sure, for callers that must pick one |
|
| 100 |
+
| `name` | Standard name of `code` or `best` |
|
| 101 |
+
| `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 |
|
| 102 |
+
| `method` | `exact`, `alias`, `history`, `split`, `no_parent`, `fuzzy`, `embedding`, `none` |
|
| 103 |
+
| `candidates` | All candidates. For duplicate names, all units with that name |
|
| 104 |
+
| `year` | The year of the table used |
|
| 105 |
+
| `source_grade` | Source grade of that year's table. In this release always `A` (official page) |
|
| 106 |
+
| `rebuilt` | Whether that year's table was rebuilt. In this release always `False` |
|
| 107 |
+
| `note` | Extra explanation |
|
| 108 |
+
|
| 109 |
+
When `confidence` is `low` or `none`, `code` is `None`.
|
| 110 |
+
|
| 111 |
+
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.
|
| 112 |
+
|
| 113 |
+
### Lookup order
|
| 114 |
+
|
| 115 |
+
1. Normalize: strip whitespace and leading/trailing punctuation, full-width to half-width. A parent such as “市辖区” is treated as not given.
|
| 116 |
+
2. Choose the table year. Without a year, the latest year is used.
|
| 117 |
+
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.
|
| 118 |
+
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.
|
| 119 |
+
5. If still not found: check whether parent and name are written together (天水市麦积区), split, and search again.
|
| 120 |
+
6. If a parent was given and nothing is found: search again without the parent.
|
| 121 |
+
7. Typo rules (`geoalign/fuzzy.py`): homophones and similar-looking characters. `low` only.
|
| 122 |
+
8. Embedding model (optional, `geoalign/embed.py`). `low` only.
|
| 123 |
+
|
| 124 |
+
### Public benchmark
|
| 125 |
+
|
| 126 |
+
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.
|
| 127 |
+
|
| 128 |
+
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.
|
| 129 |
+
|
| 130 |
+
| Question type | Questions | Share given a code | Accuracy when a code is given |
|
| 131 |
+
|---|---|---|---|
|
| 132 |
+
| Former name from a notice, with year | 224 | 100.0% | 100.0% |
|
| 133 |
+
| Abolished name from a notice, no year (answer: 2025 code) | 198 | 100.0% | 100.0% |
|
| 134 |
+
| “Parent + name” written together in a notice | 210 | 100.0% | 100.0% |
|
| 135 |
+
| Full name, with year | 299 | 100.0% | 100.0% |
|
| 136 |
+
| Full name, no year | 100 | 100.0% | 100.0% |
|
| 137 |
+
| Short form (trailing 市, 县, 区, 旗, 地区, 矿区 removed) | 323 | 100.0% | 100.0% |
|
| 138 |
+
| Short form of ethnic autonomous areas | 112 | 100.0% | 100.0% |
|
| 139 |
+
| Parent full name + full name | 210 | 100.0% | 100.0% |
|
| 140 |
+
| Duplicate name, parent given | 84 | 100.0% | 100.0% |
|
| 141 |
+
| All questions with an answer | 1,760 | 100.0% | 100.0% |
|
| 142 |
+
|
| 143 |
+
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.
|
| 144 |
+
|
| 145 |
+
**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.
|
| 146 |
+
|
| 147 |
+
### Data files
|
| 148 |
+
|
| 149 |
+
The files in `geoalign/data/` are produced by two scripts:
|
| 150 |
+
|
| 151 |
+
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.
|
| 152 |
+
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.
|
| 153 |
+
|
| 154 |
+
### Tests
|
| 155 |
+
|
| 156 |
+
```
|
| 157 |
+
python -m unittest discover -s tests
|
| 158 |
+
```
|
| 159 |
+
|
| 160 |
+
### License
|
| 161 |
+
|
| 162 |
+
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).
|
| 163 |
+
|
| 164 |
+
---
|
| 165 |
+
|
| 166 |
+
## 中文
|
| 167 |
+
|
| 168 |
+
### 做什么
|
| 169 |
+
|
| 170 |
+
1. 把地名写法变成行政区划代码。可以给年份和上级地名。
|
| 171 |
+
2. 把一年的代码换成另一年的代码。拆分、合并时给出全部去向。
|
| 172 |
+
3. 查一个地方的沿革。
|
| 173 |
+
|
| 174 |
+
没有把握时,工具库不给代码,给全部候选。
|
| 175 |
+
|
| 176 |
+
### 安装
|
| 177 |
+
|
| 178 |
+
从数据集仓库里的 wheel 安装:
|
| 179 |
+
|
| 180 |
+
```
|
| 181 |
+
pip install https://huggingface.co/datasets/WorldInsightLab/china-admin-divisions/resolve/main/geoalign/dist/geoalign-0.1.0-py3-none-any.whl
|
| 182 |
+
```
|
| 183 |
+
|
| 184 |
+
从源码安装(在 `pyproject.toml` 所在的 `geoalign/` 目录下运行):
|
| 185 |
+
|
| 186 |
+
```
|
| 187 |
+
pip install .
|
| 188 |
+
```
|
| 189 |
+
|
| 190 |
+
- 查表和错别字规则只用 Python 标准库(Python 3.8 以上),不用显卡。
|
| 191 |
+
- 向量模型后备是可选的。要装 `sentence-transformers` 和 `torch`(从源码装时可用 `pip install ".[embed]"`),还要自己准备一个中文向量模型。公开测试题不测向量模型后备。
|
| 192 |
+
|
| 193 |
+
### 数据范围
|
| 194 |
+
|
| 195 |
+
1. 2012 至 2025 年,每年年底的县级以上代码表,全部来自民政部官方页。数据和出处见数据集卡片。
|
| 196 |
+
2. 给的年份早于 2012 年时,工具库不给代码,`note` 写明“数据只从 2012 年开始”。
|
| 197 |
+
3. 给的年份晚于 2025 年时,用 2025 年的表。
|
| 198 |
+
4. **只管县级以上。不要把乡镇名交给工具库。** 去掉“镇、乡、街道”等通名以后,27,004 个不同的乡镇写法里有 1,358 个(5.0%)会被有把握地认成县级以上单位(例:“三台”→三台县)。按乡镇个数算(同名乡镇按出现次数算),38,742 个乡镇里约 12%(4,497 个)会被这样认错。认出的单位常常不是这个乡镇所在的县。
|
| 199 |
+
|
| 200 |
+
### 用法
|
| 201 |
+
|
| 202 |
+
下面的输出由上面的 wheel 在干净的虚拟环境里实际运行得到。
|
| 203 |
+
|
| 204 |
+
```python
|
| 205 |
+
from geoalign import Gazetteer
|
| 206 |
+
g = Gazetteer()
|
| 207 |
+
|
| 208 |
+
m = g.align("密云县") # 不给年份时,对到最新的代码
|
| 209 |
+
(m.code, m.name, m.confidence, m.method, m.year)
|
| 210 |
+
# ('110118', '密云区', 'medium', 'history', 2025)
|
| 211 |
+
|
| 212 |
+
g.align("密云县", year=2013).code # '110228':2013 年底还是密云县
|
| 213 |
+
g.align("朝阳区", parent="长春市").code # '220104'
|
| 214 |
+
|
| 215 |
+
m = g.align("朝阳区") # 重名,没有上级
|
| 216 |
+
(m.code, m.best, m.confidence, m.method)
|
| 217 |
+
# (None, '110105', 'low', 'exact') # 没有把握,不给代码
|
| 218 |
+
[(c.code, c.name, c.parent_name) for c in m.candidates]
|
| 219 |
+
# [('110105', '朝阳区', '北京市'), ('220104', '朝阳区', '吉林省长春市')]
|
| 220 |
+
|
| 221 |
+
m = g.align("天水市麦积区") # 上级和本级连写
|
| 222 |
+
(m.code, m.name, m.confidence, m.method)
|
| 223 |
+
# ('620503', '麦积区', 'medium', 'split')
|
| 224 |
+
|
| 225 |
+
m = g.align("密云县", year=1990) # 早于 2012 年
|
| 226 |
+
(m.code, m.confidence)
|
| 227 |
+
# (None, 'low')
|
| 228 |
+
|
| 229 |
+
g.to_year("110228", 2025)
|
| 230 |
+
# YearResult(codes=['110118'], names=['密云区'], exact=True,
|
| 231 |
+
# steps=['2014→2015:110228 密云县 → 110118 密云区(撤县设区)'])
|
| 232 |
+
|
| 233 |
+
g.to_year("130103", 2016) # 石家庄桥东区 2014 年撤销,分给两个区
|
| 234 |
+
# YearResult(codes=['130102', '130104'], names=['长安区', '桥西区'], exact=False,
|
| 235 |
+
# steps=['2014→2015:130103 桥东区 → 130102 长安区(拆分)',
|
| 236 |
+
# '2014→2015:130103 桥东区 → 130104 桥西区(拆分)'])
|
| 237 |
+
|
| 238 |
+
g.history("330103") # 杭州市下城区:2021 年并入拱墅区
|
| 239 |
+
# {'code': '330103', 'names': [{'name': '下城区', 'from': 2012, 'to': 2020}],
|
| 240 |
+
# 'events': [{'year': 2021, 'type': '合并', 'relation': '多对一', 'partial': False,
|
| 241 |
+
# 'old_code': '330103', 'old_name': '下城区', 'new_code': '330105', 'new_name': '拱墅区',
|
| 242 |
+
# 'basis': '官方变更情况', 'source_url': 'http://xzqh.mca.gov.cn/description?dcpid=2021'}]}
|
| 243 |
+
```
|
| 244 |
+
|
| 245 |
+
`align` 返回的字段:
|
| 246 |
+
|
| 247 |
+
| 字段 | 意思 |
|
| 248 |
+
|---|---|
|
| 249 |
+
| `code` | 有把握时的代码。没有把握时是 `None` |
|
| 250 |
+
| `best` | 排第一的候选。没有把握时也给,供必须取一个的调用方用 |
|
| 251 |
+
| `name` | `code` 或 `best` 的标准名称 |
|
| 252 |
+
| `confidence` | `high`:全称唯一。`medium`:简称、旧名、连写拆开以后唯一。`low`:错别字规则、向量模型、去掉上级才找到、有多个候选、泛称、早于 2012 年。`none`:找不到 |
|
| 253 |
+
| `method` | `exact`、`alias`、`history`、`split`、`no_parent`、`fuzzy`、`embedding`、`none` |
|
| 254 |
+
| `candidates` | 全部候选。重名时是全部重名单位 |
|
| 255 |
+
| `year` | 用的哪一年的表 |
|
| 256 |
+
| `source_grade` | 这一年的表的来源等级。本版只有 `A`(官方原页) |
|
| 257 |
+
| `rebuilt` | 这一年的表是不是重建的。本版都是 `False` |
|
| 258 |
+
| `note` | 补充说明 |
|
| 259 |
+
|
| 260 |
+
`confidence` 是 `low` 或 `none` 时,`code` 是 `None`。
|
| 261 |
+
|
| 262 |
+
泛称(“市区”“新区”“城区”“郊区”“矿区”“东区”“西区”等)单独出现时最多给 `low`。给了上级、上级把它确定成一个单位时(例:上级“长治市”+“城区”),照常给代码。
|
| 263 |
+
|
| 264 |
+
### 查的顺序
|
| 265 |
+
|
| 266 |
+
1. 规范写法:去空白、首尾标点,全角换半角。“市辖区”这类上级当作没给。
|
| 267 |
+
2. 定用哪一年的表。不给年份时用最新一年。
|
| 268 |
+
3. 在这一年的表里找全称,再找简称(去掉通名、民族自治地方的简称、旗的简称、民族区去掉民族名)。给了上级时用上级筛。去掉通名后只剩 1 个字的不作简称。
|
| 269 |
+
4. 这一年的表里没有:到所有年份找,再沿官方变更表换成这一年的代码。拆分时沿主要承继走(变更表 `main = 是`)。公告没有说主要承继时,给全部去向,不给代码。
|
| 270 |
+
5. 还没有:看是不是上级和本级连写(天水市麦积区),拆开再找。
|
| 271 |
+
6. 给了上级还找不到:去掉上级再找。
|
| 272 |
+
7. 错别字规则(`geoalign/fuzzy.py`):同音字、形近字。只给 `low`。
|
| 273 |
+
8. 向量模型(可选,`geoalign/embed.py`)。只给 `low`。
|
| 274 |
+
|
| 275 |
+
### 公开测试题
|
| 276 |
+
|
| 277 |
+
公开测试题在 `benchmark/`:`make_questions.py` 生成题目,`run.py` 测。题目只用数据集里的官方代码表和公告原句,按写明的规则生成,答案按年底口径。生成规则写在 `make_questions.py` 开头。
|
| 278 |
+
|
| 279 |
+
结果(`benchmark/results.md`,只查表和错别字规则,不用向量模型)。我们用安装好的 wheel 重跑 `run.py`,结果和这张表相同。
|
| 280 |
+
|
| 281 |
+
| 题的种类 | 题数 | 给代码的比例 | 给代码时的正确率 |
|
| 282 |
+
|---|---|---|---|
|
| 283 |
+
| 公告里的旧名称,给年份 | 224 | 100.0% | 100.0% |
|
| 284 |
+
| 公告里撤销的旧名称,不给年份(答案是 2025 年的代码) | 198 | 100.0% | 100.0% |
|
| 285 |
+
| 公告里的“上级 + 名称”连写 | 210 | 100.0% | 100.0% |
|
| 286 |
+
| 全称,给年份 | 299 | 100.0% | 100.0% |
|
| 287 |
+
| 全称,不给年份 | 100 | 100.0% | 100.0% |
|
| 288 |
+
| 简称(去掉末尾的市、县、区、旗、地区、矿区) | 323 | 100.0% | 100.0% |
|
| 289 |
+
| 民族自治地方的简称 | 112 | 100.0% | 100.0% |
|
| 290 |
+
| 上级全称 + 全称 | 210 | 100.0% | 100.0% |
|
| 291 |
+
| 重名,给了上级 | 84 | 100.0% | 100.0% |
|
| 292 |
+
| 有答案的题合计 | 1,760 | 100.0% | 100.0% |
|
| 293 |
+
|
| 294 |
+
答案是“不应给代码”的 180 道题(重名没给上级、简称对得上几个单位、早于 2012 年、泛称、2026 年才设立的单位),错给代码 0 道。
|
| 295 |
+
|
| 296 |
+
**这套题容易,不代表真实数据上的成绩。** 出题的变形规则(去掉末尾的市、县、区、旗,去掉民族名,上级 + 全称)和工具库的简称、连写规则基本相同,所以这些类别接近 100% 是预期的。这套题主要检验规则的实现没有错、重名时不乱给代码。题里的写法都是官方写法或按简单规则变出来的,没有错别字,没有乱写法。真实数据里有错别字、残缺的名称、乡镇名混入。在这类数据上,给代码的比例会低得多,给代码时也可能出错。错别字规则没有公开测试题。
|
| 297 |
+
|
| 298 |
+
### 数据文件
|
| 299 |
+
|
| 300 |
+
`geoalign/data/` 里的文件由下面两个脚本生成:
|
| 301 |
+
|
| 302 |
+
1. `python -m geoalign.build_data <数据集的 data 目录>`:打包代码表和变更表。脚本检查范围:代码表只收 2012 年及以后,变更表只收 2013 年及以后。
|
| 303 |
+
2. `python tools/build_confusion.py <years.csv> <NotoSansCJK-Regular.ttc>`:生成错别字规则用的同音字、形近字表。只在生成时要 Pillow、numpy、pypinyin 和 Noto Sans CJK 字体。
|
| 304 |
+
|
| 305 |
+
### 测试
|
| 306 |
+
|
| 307 |
+
```
|
| 308 |
+
python -m unittest discover -s tests
|
| 309 |
+
```
|
| 310 |
+
|
| 311 |
+
### 许可
|
| 312 |
+
|
| 313 |
+
代码按 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)。
|
geoalign/benchmark/make_questions.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""生成公开测试题(benchmark/questions.csv)。只用发布的数据集:代码表 years.csv 和变更表 changes.csv 的公告原句。
|
| 2 |
+
|
| 3 |
+
用法:python benchmark/make_questions.py <数据集 data 目录>
|
| 4 |
+
答案一律按年底口径:给了年份时,答案是那一年年底的官方代码表里的代码。
|
| 5 |
+
|
| 6 |
+
题的种类(kind):
|
| 7 |
+
notice_old 公告原句里的旧名称(例:“撤销万全县”里的“万全县”),年份是公告前一年,答案是前一年的表里的代码。
|
| 8 |
+
有重名时:公告写了上级,题目给上级,答案是那个单位;公告没写上级,答案是“不应给代码”。
|
| 9 |
+
notice_concat 公告原句里“上级 + 名称”连写(例:“张家口市万全区”),年份是公告那一年。
|
| 10 |
+
full 代码表里的全称。
|
| 11 |
+
short 全称去掉末尾的“市、县、区、旗”或“地区、矿区”(剩下至少 2 个字),规则见 short()。
|
| 12 |
+
判断对得上几个单位时,也算自治地方只剩地名的写法(例:宽城满族自治县 → 宽城)。去掉以后在同一年的表里只对得上 1 个单位时,答案是那个单位;
|
| 13 |
+
对得上几个单位时,答案是“不应给代码”。
|
| 14 |
+
autonomy 民族自治州、县去掉民族名(例:凉山彝族自治州 → 凉山州)。规则见 autonomy_short()。
|
| 15 |
+
concat 上级全称 + 全称(例:天水市麦积区)。
|
| 16 |
+
full_noyear 2025 年表里的全称,不给年份。
|
| 17 |
+
old_noyear 公告里撤销的旧名称,不给年份。答案沿变更表 main = 是 的行走到 2025 年(条件见程序)。
|
| 18 |
+
homonym_bare 同一年县级有重名的名称,不给上级。答案是“不应给代码”。
|
| 19 |
+
homonym_parent 同上,给上级全称。答案是那个单位。
|
| 20 |
+
before 给的年份早于 2012 年。答案是“不应给代码”。
|
| 21 |
+
generic 泛称(市区、新区、城区、郊区、矿区、市、区、县)。答案是“不应给代码”。
|
| 22 |
+
after_2025 2026 年才设立的单位,年份写 2025。答案是“不应给代码”。
|
| 23 |
+
expect 列:6 位代码,或 ABSTAIN(不应给代码)。
|
| 24 |
+
"""
|
| 25 |
+
import csv, os, random, re, sys, collections
|
| 26 |
+
|
| 27 |
+
FIRST, LAST = 2012, 2025
|
| 28 |
+
GENERIC = ["市区", "新区", "城区", "郊区", "矿区", "市", "区", "县"]
|
| 29 |
+
NEW_2026 = [("岑岭县", "新疆维吾尔自治区"), ("草湖市", "新疆维吾尔自治区")] # 2026 年公告设立,不在 2025 年底的表里
|
| 30 |
+
SEED = 20261118
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# 55 个少数民族的名称,用来认出自治州、自治县名称里的民族名
|
| 34 |
+
MINZU = ("蒙古 回 藏 维吾尔 苗 彝 壮 布依 朝鲜 满 侗 瑶 白 土家 哈尼 哈萨克 傣 黎 傈僳 佤 畲 高山 拉祜 水 东乡 纳西 景颇 柯尔克孜 土 "
|
| 35 |
+
"达斡尔 仫佬 羌 布朗 撒拉 毛南 仡佬 锡伯 阿昌 普米 塔吉克 怒 乌孜别克 俄罗斯 鄂温克 德昂 保安 裕固 京 塔塔尔 独龙 "
|
| 36 |
+
"鄂伦春 赫哲 门巴 珞巴 基诺").split()
|
| 37 |
+
MINZU_RE = "(?:" + "|".join(sorted(MINZU, key=len, reverse=True)) + ")族"
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def autonomy_short(name):
|
| 41 |
+
"""民族自治州、县、旗:去掉全部民族名和“自治”。例:凉山彝族自治州→凉山州,积石山保安族东乡族撒拉族自治县→积石山县。
|
| 42 |
+
不是这种名称时返回 None。"""
|
| 43 |
+
m = re.match("^(.{2,}?)(?:" + MINZU_RE + ")+自治(州|县|旗)$", name)
|
| 44 |
+
return m[1] + m[2] if m else None
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def short(name):
|
| 48 |
+
"""去掉末尾的“市、县、区、旗”,剩下至少 2 个字。“地区”“矿区”去掉两个字。自治区、自治州、自治县、自治旗、林区、特区不处理。"""
|
| 49 |
+
if name.endswith(("自治区", "自治县", "自治旗", "自治州", "林区", "特区")):
|
| 50 |
+
return None
|
| 51 |
+
if name.endswith(("地区", "矿区")) and len(name) >= 4: # 白云鄂博矿区 → 白云鄂博,不写成“白云鄂博矿”
|
| 52 |
+
return name[:-2]
|
| 53 |
+
if len(name) >= 3 and name[-1] in "市县区旗":
|
| 54 |
+
return name[:-1]
|
| 55 |
+
return None
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def main(ds, out):
|
| 59 |
+
T = collections.defaultdict(dict) # year → code → (name, parent_code, level)
|
| 60 |
+
src = {}
|
| 61 |
+
for r in csv.DictReader(open(os.path.join(ds, "years.csv"), encoding="utf-8")):
|
| 62 |
+
y = int(r["year"])
|
| 63 |
+
T[y][r["code"]] = (r["name"], r["parent_code"], r["level"])
|
| 64 |
+
src.setdefault(y, r["archive_url"] or r["source_url"])
|
| 65 |
+
rnd = random.Random(SEED)
|
| 66 |
+
Q = []
|
| 67 |
+
|
| 68 |
+
def add(kind, text, year, expect, source, parent="", note=""):
|
| 69 |
+
Q.append(dict(kind=kind, text=text, parent=parent, year=year if year is not None else "", expect=expect,
|
| 70 |
+
source=source, note=note))
|
| 71 |
+
|
| 72 |
+
def by_name(y):
|
| 73 |
+
d = collections.defaultdict(list)
|
| 74 |
+
for c, (n, p, lv) in T[y].items():
|
| 75 |
+
d[n].append(c)
|
| 76 |
+
return d
|
| 77 |
+
|
| 78 |
+
def parent_name(y, c):
|
| 79 |
+
p = T[y][c][1]
|
| 80 |
+
return T[y][p][0] if p in T[y] else ""
|
| 81 |
+
|
| 82 |
+
# ---------- 公告原句 ----------
|
| 83 |
+
seen = set()
|
| 84 |
+
for r in csv.DictReader(open(os.path.join(ds, "changes.csv"), encoding="utf-8")):
|
| 85 |
+
if r["basis"] != "官方变更情况" or not r["evidence"]:
|
| 86 |
+
continue
|
| 87 |
+
ny, sent, url = int(r["notice_year"]), r["evidence"], r["source_url"]
|
| 88 |
+
for y, kind in ((ny - 1, "notice_old"), (ny, "notice_concat")):
|
| 89 |
+
if y not in T:
|
| 90 |
+
continue
|
| 91 |
+
names = by_name(y)
|
| 92 |
+
for n in sorted(names, key=len, reverse=True):
|
| 93 |
+
if len(n) < 2 or n not in sent:
|
| 94 |
+
continue
|
| 95 |
+
for c in names[n]:
|
| 96 |
+
if T[y][c][2] != "county":
|
| 97 |
+
continue
|
| 98 |
+
pn = parent_name(y, c)
|
| 99 |
+
if kind == "notice_concat":
|
| 100 |
+
if pn and (pn + n) in sent and (pn + n, y) not in seen:
|
| 101 |
+
seen.add((pn + n, y))
|
| 102 |
+
add(kind, pn + n, y, c, url, note=sent[:80])
|
| 103 |
+
elif any(k + n in sent for k in ("撤销", "原", "撤销" + pn, "原" + pn)):
|
| 104 |
+
if len(names[n]) == 1:
|
| 105 |
+
key, parent, expect = (n, y, ""), "", c
|
| 106 |
+
elif pn and pn + n in sent: # 公告写了上级,题目也给上级
|
| 107 |
+
key, parent, expect = (n, y, pn), pn, c
|
| 108 |
+
else:
|
| 109 |
+
key, parent, expect = (n, y, ""), "", "ABSTAIN"
|
| 110 |
+
if key in seen:
|
| 111 |
+
continue
|
| 112 |
+
seen.add(key)
|
| 113 |
+
add(kind, n, y, expect, url, parent=parent, note=sent[:80])
|
| 114 |
+
|
| 115 |
+
# ---------- 按规则生成 ----------
|
| 116 |
+
years = list(range(FIRST, LAST + 1))
|
| 117 |
+
for _ in range(300):
|
| 118 |
+
y = rnd.choice(years); c = rnd.choice(sorted(T[y])); n = T[y][c][0]
|
| 119 |
+
add("full", n, y, c if len(by_name(y)[n]) == 1 else "ABSTAIN", src[y])
|
| 120 |
+
for y in years:
|
| 121 |
+
names = by_name(y)
|
| 122 |
+
shorts = collections.defaultdict(set)
|
| 123 |
+
for c, (n, p, lv) in T[y].items():
|
| 124 |
+
au = autonomy_short(n)
|
| 125 |
+
# 判断“对得上几个单位”时,也算上自治地方只剩地名的写法(宽城满族自治县 → 宽城),
|
| 126 |
+
# 这样“宽城”同时对得上宽城区和宽城满族自治县,答案是“不应给代码”
|
| 127 |
+
for s in {n, short(n), au, au[:-1] if au and len(au) >= 3 else None} - {None}:
|
| 128 |
+
shorts[s].add(c)
|
| 129 |
+
cs = sorted(c for c in T[y] if short(T[y][c][0]))
|
| 130 |
+
for c in rnd.sample(cs, 25):
|
| 131 |
+
s = short(T[y][c][0])
|
| 132 |
+
add("short", s, y, c if shorts[s] == {c} else "ABSTAIN", src[y], note="规则:去掉末尾的市、县、区、旗")
|
| 133 |
+
au = sorted(c for c in T[y] if autonomy_short(T[y][c][0]))
|
| 134 |
+
for c in rnd.sample(au, min(8, len(au))):
|
| 135 |
+
s = autonomy_short(T[y][c][0])
|
| 136 |
+
add("autonomy", s, y, c if shorts[s] == {c} else "ABSTAIN", src[y], note="规则:去掉民族名和“自治”")
|
| 137 |
+
county = sorted(c for c in T[y] if T[y][c][2] == "county" and parent_name(y, c))
|
| 138 |
+
for c in rnd.sample(county, 15):
|
| 139 |
+
add("concat", parent_name(y, c) + T[y][c][0], y, c, src[y], note="规则:上级全称 + 全称")
|
| 140 |
+
homo = sorted(n for n, cs2 in names.items() if len(cs2) > 1 and all(T[y][x][2] == "county" for x in cs2))
|
| 141 |
+
for n in rnd.sample(homo, 6):
|
| 142 |
+
add("homonym_bare", n, y, "ABSTAIN", src[y])
|
| 143 |
+
c = rnd.choice(sorted(names[n])); pn = parent_name(y, c)
|
| 144 |
+
if sum(parent_name(y, x) == pn for x in names[n]) == 1:
|
| 145 |
+
add("homonym_parent", n, y, c, src[y], parent=pn)
|
| 146 |
+
# ---------- 不给年份的题 ----------
|
| 147 |
+
# full_noyear:2025 年表里的全称,不给年份。答案是 2025 年的代码。
|
| 148 |
+
names25 = by_name(LAST)
|
| 149 |
+
for c in rnd.sample(sorted(c for c in T[LAST] if len(names25[T[LAST][c][0]]) == 1), 100):
|
| 150 |
+
add("full_noyear", T[LAST][c][0], None, c, src[LAST], note="不给年份")
|
| 151 |
+
# old_noyear:公告里撤销的旧名称,不给年份。答案是沿变更表 main = 是 的行走到 2025 年的代码。
|
| 152 |
+
# 只出这种题:这个名称在 2012 至 2025 年所有的表里只对应 1 个代码,2025 年的表里没有这个名称,而且每一步只有 1 个主要承继。
|
| 153 |
+
main_rows = collections.defaultdict(list)
|
| 154 |
+
for r in csv.DictReader(open(os.path.join(ds, "changes.csv"), encoding="utf-8")):
|
| 155 |
+
if r["main"] == "是" and r["old_code"] and r["new_code"]:
|
| 156 |
+
main_rows[(int(r["year"]), r["old_code"])].append(r["new_code"])
|
| 157 |
+
codes_of = collections.defaultdict(set)
|
| 158 |
+
for y in years:
|
| 159 |
+
for c, (n, p, lv) in T[y].items():
|
| 160 |
+
codes_of[n].add(c)
|
| 161 |
+
|
| 162 |
+
def walk(code, y0):
|
| 163 |
+
for y in range(y0 + 1, LAST + 1):
|
| 164 |
+
if code in T[y]:
|
| 165 |
+
continue
|
| 166 |
+
nxt = main_rows.get((y, code), [])
|
| 167 |
+
if len(nxt) != 1:
|
| 168 |
+
return None
|
| 169 |
+
code = nxt[0]
|
| 170 |
+
return code if code in T[LAST] else None
|
| 171 |
+
|
| 172 |
+
for q in [q for q in Q if q["kind"] == "notice_old" and q["expect"] != "ABSTAIN" and not q["parent"]]:
|
| 173 |
+
n = q["text"]
|
| 174 |
+
if len(codes_of[n]) == 1 and n not in names25:
|
| 175 |
+
ans = walk(q["expect"], int(q["year"]))
|
| 176 |
+
if ans:
|
| 177 |
+
add("old_noyear", n, None, ans, q["source"], note="不给年份,答案沿变更表 main = 是 走到 2025 年")
|
| 178 |
+
for _ in range(50):
|
| 179 |
+
c = rnd.choice(sorted(T[LAST])); add("before", T[LAST][c][0], rnd.randint(1990, FIRST - 1), "ABSTAIN", "", note="早于数据第一年")
|
| 180 |
+
for g in GENERIC:
|
| 181 |
+
add("generic", g, None, "ABSTAIN", "", note="泛称")
|
| 182 |
+
for n, p in NEW_2026:
|
| 183 |
+
add("after_2025", n, LAST, "ABSTAIN", "", note="2026 年设立")
|
| 184 |
+
for i, q in enumerate(Q):
|
| 185 |
+
q["id"] = f"q{i + 1:04d}"
|
| 186 |
+
with open(out, "w", newline="", encoding="utf-8") as fh:
|
| 187 |
+
w = csv.DictWriter(fh, ["id", "kind", "text", "parent", "year", "expect", "source", "note"]); w.writeheader(); w.writerows(Q)
|
| 188 |
+
print(len(Q), collections.Counter(q["kind"] for q in Q))
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
if __name__ == "__main__":
|
| 192 |
+
here = os.path.dirname(os.path.abspath(__file__))
|
| 193 |
+
main(sys.argv[1] if len(sys.argv) > 1 else os.path.join(here, "..", "..", "dataset", "data"), os.path.join(here, "questions.csv"))
|
geoalign/benchmark/questions.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
geoalign/benchmark/results.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
| 题的种类 | 题数 | 给代码的比例 | 给代码时的正确率 | 排第一的候选正确率 | 错给代码的比例 |
|
| 2 |
+
|---|---|---|---|---|---|
|
| 3 |
+
| after_2025(不应给代码) | 2 | | | | 0.0% |
|
| 4 |
+
| autonomy | 112 | 100.0% | 100.0% | 100.0% | |
|
| 5 |
+
| before(不应给代码) | 50 | | | | 0.0% |
|
| 6 |
+
| concat | 210 | 100.0% | 100.0% | 100.0% | |
|
| 7 |
+
| full | 299 | 100.0% | 100.0% | 100.0% | |
|
| 8 |
+
| full_noyear | 100 | 100.0% | 100.0% | 100.0% | |
|
| 9 |
+
| full(不应给代码) | 1 | | | | 0.0% |
|
| 10 |
+
| generic(不应给代码) | 8 | | | | 0.0% |
|
| 11 |
+
| homonym_bare(不应给代码) | 84 | | | | 0.0% |
|
| 12 |
+
| homonym_parent | 84 | 100.0% | 100.0% | 100.0% | |
|
| 13 |
+
| notice_concat | 210 | 100.0% | 100.0% | 100.0% | |
|
| 14 |
+
| notice_old | 224 | 100.0% | 100.0% | 100.0% | |
|
| 15 |
+
| notice_old(不应给代码) | 8 | | | | 0.0% |
|
| 16 |
+
| old_noyear | 198 | 100.0% | 100.0% | 100.0% | |
|
| 17 |
+
| short | 323 | 100.0% | 100.0% | 100.0% | |
|
| 18 |
+
| short(不应给代码) | 27 | | | | 0.0% |
|
| 19 |
+
| 有答案的题合计 | 1760 | 100.0% | 100.0% | 100.0% | |
|
| 20 |
+
|
| 21 |
+
给错代码的题 0 道:
|
geoalign/benchmark/run.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""在公开测试题上测工具库。用法:python benchmark/run.py(只查表和错别字规则,不用向量模型)
|
| 2 |
+
报每种题:题数;给代码的比例;给代码时的正确率;排第一的候选(best)的正确率。
|
| 3 |
+
答案是 ABSTAIN 的题报:错给代码的比例(越低越好)。
|
| 4 |
+
"""
|
| 5 |
+
import csv, json, os, sys, collections
|
| 6 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 7 |
+
sys.path.insert(0, os.path.dirname(HERE))
|
| 8 |
+
from geoalign import Gazetteer # noqa: E402
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def main():
|
| 12 |
+
g = Gazetteer()
|
| 13 |
+
Q = list(csv.DictReader(open(os.path.join(HERE, "questions.csv"), encoding="utf-8")))
|
| 14 |
+
S = collections.defaultdict(collections.Counter)
|
| 15 |
+
wrong = []
|
| 16 |
+
for q in Q:
|
| 17 |
+
m = g.align(q["text"], parent=q["parent"] or None, year=int(q["year"]) if q["year"] else None)
|
| 18 |
+
s = S[q["kind"] + ("(不应给代码)" if q["expect"] == "ABSTAIN" else "")]
|
| 19 |
+
s["n"] += 1
|
| 20 |
+
if q["expect"] == "ABSTAIN":
|
| 21 |
+
s["wrong_code"] += m.code is not None
|
| 22 |
+
if m.code is not None:
|
| 23 |
+
wrong.append((q["id"], q["kind"], q["text"], q["year"], q["expect"], m.code, m.method))
|
| 24 |
+
else:
|
| 25 |
+
s["coded"] += m.code is not None
|
| 26 |
+
s["coded_right"] += m.code == q["expect"]
|
| 27 |
+
s["best_right"] += (m.code or m.best) == q["expect"]
|
| 28 |
+
if m.code is not None and m.code != q["expect"]:
|
| 29 |
+
wrong.append((q["id"], q["kind"], q["text"], q["year"], q["expect"], m.code, m.method))
|
| 30 |
+
rows = []
|
| 31 |
+
tot = collections.Counter()
|
| 32 |
+
for k in sorted(S):
|
| 33 |
+
s = S[k]
|
| 34 |
+
if "wrong_code" in s or "(不应给代码)" in k:
|
| 35 |
+
rows.append((k, s["n"], "", "", "", f"{s['wrong_code'] / s['n']:.1%}"))
|
| 36 |
+
else:
|
| 37 |
+
tot.update(s)
|
| 38 |
+
rows.append((k, s["n"], f"{s['coded'] / s['n']:.1%}", f"{s['coded_right'] / max(s['coded'], 1):.1%}",
|
| 39 |
+
f"{s['best_right'] / s['n']:.1%}", ""))
|
| 40 |
+
rows.append(("有答案的题合计", tot["n"], f"{tot['coded'] / tot['n']:.1%}", f"{tot['coded_right'] / max(tot['coded'], 1):.1%}",
|
| 41 |
+
f"{tot['best_right'] / tot['n']:.1%}", ""))
|
| 42 |
+
print("| 题的种类 | 题数 | 给代码的比例 | 给代码时的正确率 | 排第一的候选正确率 | 错给代码的比例 |")
|
| 43 |
+
print("|---|---|---|---|---|---|")
|
| 44 |
+
for r in rows:
|
| 45 |
+
print("| " + " | ".join(str(x) for x in r) + " |")
|
| 46 |
+
print(f"\n给错代码的题 {len(wrong)} 道:")
|
| 47 |
+
for w in wrong:
|
| 48 |
+
print(" ", *w)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
if __name__ == "__main__":
|
| 52 |
+
main()
|
geoalign/dist/geoalign-0.1.0-py3-none-any.whl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7601a390bfdea1edd94157e72434ab1172ed95a44e08b60ad48f72735321b945
|
| 3 |
+
size 566106
|
geoalign/dist/geoalign-0.1.0.tar.gz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8147dd2b78668e295ca6817ed24af105549add15c3b9f97907bf102eb23c4c2b
|
| 3 |
+
size 568279
|
geoalign/geoalign/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""geoalign:把中国县级以上行政区划的名称对到官方代码,并在年份之间换算代码。数据范围 2012 至 2025 年。"""
|
| 2 |
+
from .core import Gazetteer, Match, YearResult, Candidate # noqa: F401
|
| 3 |
+
|
| 4 |
+
__version__ = "0.1.0"
|
geoalign/geoalign/build_data.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""把数据集(dataset/data/years.csv、changes.csv)压成工具库自带的数据文件(geoalign/data/)。
|
| 2 |
+
|
| 3 |
+
用法(在发布目录里):python -m geoalign.build_data ../dataset/data
|
| 4 |
+
数据集更新以后重跑一次。工具库运行时只读 geoalign/data/。
|
| 5 |
+
范围检查:代码表只收 2012 年及以后的行;变更表只收 2013 年及以后的行。不满足时报错停止。
|
| 6 |
+
"""
|
| 7 |
+
import csv, gzip, io, json, os, sys
|
| 8 |
+
|
| 9 |
+
PKG = os.path.dirname(os.path.abspath(__file__))
|
| 10 |
+
OUT = os.path.join(PKG, "data")
|
| 11 |
+
FIRST_YEAR, FIRST_CHANGE_YEAR = 2012, 2013
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def main(ds):
|
| 15 |
+
os.makedirs(OUT, exist_ok=True)
|
| 16 |
+
meta = {}
|
| 17 |
+
with gzip.GzipFile(os.path.join(OUT, "years.csv.gz"), "wb", mtime=0) as gz:
|
| 18 |
+
fh = io.TextIOWrapper(gz, encoding="utf-8", newline="")
|
| 19 |
+
w = csv.writer(fh)
|
| 20 |
+
w.writerow(["year", "code", "name"])
|
| 21 |
+
for r in csv.DictReader(open(os.path.join(ds, "years.csv"), encoding="utf-8")):
|
| 22 |
+
if int(r["year"]) < FIRST_YEAR:
|
| 23 |
+
raise SystemExit(f"范围外的行:{r['year']} {r['code']}")
|
| 24 |
+
w.writerow([r["year"], r["code"], r["name"]])
|
| 25 |
+
meta.setdefault(r["year"], dict(source_grade="A", rebuilt=False, source_url=r["source_url"],
|
| 26 |
+
archive_url=r["archive_url"], fetched=r["fetched"]))
|
| 27 |
+
fh.flush(); fh.detach()
|
| 28 |
+
json.dump(meta, open(os.path.join(OUT, "years_meta.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=0)
|
| 29 |
+
cols = ["year", "change_type", "relation", "partial", "main", "old_code", "old_name", "new_code", "new_name",
|
| 30 |
+
"basis", "notice_year", "source_url"]
|
| 31 |
+
with gzip.GzipFile(os.path.join(OUT, "changes.csv.gz"), "wb", mtime=0) as gz:
|
| 32 |
+
fh = io.TextIOWrapper(gz, encoding="utf-8", newline="")
|
| 33 |
+
w = csv.writer(fh)
|
| 34 |
+
w.writerow(cols)
|
| 35 |
+
for r in csv.DictReader(open(os.path.join(ds, "changes.csv"), encoding="utf-8")):
|
| 36 |
+
if int(r["year"]) < FIRST_CHANGE_YEAR:
|
| 37 |
+
raise SystemExit(f"范围外的变更行:{r['year']}")
|
| 38 |
+
w.writerow([r[c] for c in cols])
|
| 39 |
+
fh.flush(); fh.detach()
|
| 40 |
+
for f in sorted(os.listdir(OUT)):
|
| 41 |
+
print(f, os.path.getsize(os.path.join(OUT, f)))
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
if __name__ == "__main__":
|
| 45 |
+
main(sys.argv[1] if len(sys.argv) > 1 else os.path.join(os.path.dirname(os.path.dirname(PKG)), "dataset", "data"))
|
geoalign/geoalign/core.py
ADDED
|
@@ -0,0 +1,429 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""地名对齐的查表部分。只用 Python 标准库,不用显卡。
|
| 2 |
+
|
| 3 |
+
主要入口:
|
| 4 |
+
g = Gazetteer()
|
| 5 |
+
g.align("密云县") # 地名 → 现行代码
|
| 6 |
+
g.align("密云县", year=2013) # 地名 → 2013 年底的代码(数据从 2012 年开始)
|
| 7 |
+
g.align("朝阳区", parent="长春市") # 带上级
|
| 8 |
+
g.to_year("110228", 2025) # 旧代码 → 指定年份的代码
|
| 9 |
+
g.history("110118") # 一个地方的沿革
|
| 10 |
+
|
| 11 |
+
align 的结果(Match):
|
| 12 |
+
code 有把握时的代码。没有把握时是 None
|
| 13 |
+
name code 或 best 的标准名称
|
| 14 |
+
best 排第一的候选(没有把握时也给,供需要强行取一个的调用方用)
|
| 15 |
+
confidence high:全称唯一;medium:简称、旧名、连写拆开以后唯一;low:模糊匹配、向量模型、去掉上级、多个候选、泛称、早于 2012 年;none:找不到
|
| 16 |
+
method exact / alias / history / split / no_parent / fuzzy / embedding / none
|
| 17 |
+
candidates 全部候选(重名时就是全部重名单位)
|
| 18 |
+
year 用的哪一年的表
|
| 19 |
+
source_grade 这一年的表的来源等级。发布版只有 A(官方原页)
|
| 20 |
+
rebuilt 这一年的表是不是重建的。发布版都是 False
|
| 21 |
+
note 补充说明
|
| 22 |
+
"""
|
| 23 |
+
import csv, gzip, json, os, re
|
| 24 |
+
from collections import defaultdict
|
| 25 |
+
from dataclasses import dataclass, field
|
| 26 |
+
from typing import List, Optional
|
| 27 |
+
|
| 28 |
+
DATA = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data")
|
| 29 |
+
|
| 30 |
+
SUFFIX = re.compile(r"(各族自治县|自治县|自治旗|自治州|特别行政区|维吾尔自治区|壮族自治区|回族自治区|自治区|林区|特区|地区|新区|矿区|行政委员会|省|市|县|区|旗|盟)$")
|
| 31 |
+
ETHNIC = sorted("蒙古 回 藏 维吾尔 苗 彝 壮 布依 朝鲜 满 侗 瑶 白 土家 哈尼 哈萨克 傣 黎 傈僳 佤 畲 高山 拉祜 水 东乡 纳西 景颇 柯尔克孜 土 达斡尔 仫佬 羌 布朗 撒拉 毛南 仡佬 锡伯 阿昌 普米 塔吉克 怒 乌孜别克 俄罗斯 鄂温克 德昂 保安 裕固 京 塔塔尔 独龙 鄂伦春 赫哲 门巴 珞巴 基诺".split(), key=len, reverse=True)
|
| 32 |
+
ETH_RE = re.compile("(" + "|".join(ETHNIC) + ")族?$")
|
| 33 |
+
LV_ORDER = {"prefecture": 0, "county": 1, "province": 2}
|
| 34 |
+
# 这些“上级”不是地名,当作没给
|
| 35 |
+
NOT_PARENT = {"市辖区", "县", "省直辖县级行政区划", "自治区直辖县级行政区划", "省直辖", "直辖县", "全国", "中国", "中华人民共和国"}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# 泛称:县级单位里真实存在过这些名字(例:濮阳“市区”、唐山“新区”、大同“城区”),但在一般数据里它们几乎都是泛指。
|
| 39 |
+
# 查到这些名字时最多给 low。
|
| 40 |
+
GENERIC = {"市区", "新区", "郊区", "城区", "矿区", "东区", "西区", "南区", "北区", "市", "区", "县", "新城区", "老城区", "开发区", "高新区"}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def stem(name):
|
| 44 |
+
"""去掉一次通名:荆州市 → 荆州。“林区”只在神农架林区算通名(碑林区 → 碑林,不是“碑”)。"""
|
| 45 |
+
if name.endswith("林区") and name != "神农架林区":
|
| 46 |
+
return name[:-1]
|
| 47 |
+
s2 = SUFFIX.sub("", name)
|
| 48 |
+
return s2 if s2 else name
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def level(code):
|
| 52 |
+
if code.endswith("0000"):
|
| 53 |
+
return "province"
|
| 54 |
+
if code.endswith("00"):
|
| 55 |
+
return "prefecture"
|
| 56 |
+
return "county"
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def autonomy_aliases(name):
|
| 60 |
+
"""民族自治地方的简称:凉山彝族自治州 → 凉山、凉山州。"""
|
| 61 |
+
m = re.search(r"(各族自治县|自治州|自治县|自治旗)$", name)
|
| 62 |
+
if not m:
|
| 63 |
+
return []
|
| 64 |
+
core = name[:m.start()]
|
| 65 |
+
for _ in range(4):
|
| 66 |
+
c2 = ETH_RE.sub("", core)
|
| 67 |
+
if c2 == core or len(c2) < 2:
|
| 68 |
+
break
|
| 69 |
+
core = c2
|
| 70 |
+
if core == name[:m.start()] and m.group(1) != "各族自治县":
|
| 71 |
+
return []
|
| 72 |
+
tail = {"自治州": "州", "自治县": "县", "各族自治县": "县", "自治旗": "旗"}[m.group(1)]
|
| 73 |
+
return [core, core + tail]
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def extra_aliases(name):
|
| 77 |
+
"""补充的写法规则。这些规则是看过早期测试题(不公开)的错误以后加的:
|
| 78 |
+
1. 民族区去掉民族名:顺河回族区 → 顺河区。
|
| 79 |
+
2. 少写“族”字:阿克塞哈萨克族自治县 → 阿克塞哈萨克自治县。
|
| 80 |
+
3. 内蒙古的旗的通行简称:首字 + 左/右 + 前/中/后 + 旗。鄂托克前旗 → 鄂前旗,科尔沁右翼前旗 → 科右前旗。
|
| 81 |
+
4. 民族自治旗去掉“族自治”:鄂温克族自治旗 → 鄂温克旗。"""
|
| 82 |
+
out = []
|
| 83 |
+
m = re.match(r"^(.+?)(?:" + "|".join(ETHNIC) + r")族区$", name)
|
| 84 |
+
if m and len(m.group(1)) >= 2:
|
| 85 |
+
out.append(m.group(1) + "区")
|
| 86 |
+
if "族自治" in name:
|
| 87 |
+
out.append(name.replace("族自治", "自治"))
|
| 88 |
+
m = re.match(r"^(.+?)(左翼|右翼)?(前|中|后|左|右)旗$", name)
|
| 89 |
+
if m and len(m.group(1)) >= 2:
|
| 90 |
+
side = (m.group(2) or "")[:1]
|
| 91 |
+
out.append(m.group(1)[0] + side + m.group(3) + "旗")
|
| 92 |
+
m = re.match(r"^(.+)族自治旗$", name)
|
| 93 |
+
if m:
|
| 94 |
+
out.append(m.group(1) + "旗")
|
| 95 |
+
return [a for a in out if a != name]
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
_FW = {ord(c): ord(c) - 0xFEE0 for c in "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"}
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def normalize(s):
|
| 102 |
+
"""去空白、首尾的标点,全角字母数字换半角。"""
|
| 103 |
+
if s is None:
|
| 104 |
+
return ""
|
| 105 |
+
s = str(s).translate(_FW)
|
| 106 |
+
s = re.sub(r"[\s \xa0]", "", s)
|
| 107 |
+
s = re.sub(r"^[\.。·,,、;;::\-_*#\"'“”‘’()()\[\]【】]+|[\.。·,,、;;::\-_*#\"'“”‘’()()\[\]【】]+$", "", s)
|
| 108 |
+
return s
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
@dataclass
|
| 112 |
+
class Candidate:
|
| 113 |
+
code: str
|
| 114 |
+
name: str
|
| 115 |
+
level: str
|
| 116 |
+
parent_name: str = ""
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
@dataclass
|
| 120 |
+
class Match:
|
| 121 |
+
query: str
|
| 122 |
+
code: Optional[str]
|
| 123 |
+
name: Optional[str]
|
| 124 |
+
best: Optional[str]
|
| 125 |
+
confidence: str
|
| 126 |
+
method: str
|
| 127 |
+
candidates: List[Candidate] = field(default_factory=list)
|
| 128 |
+
year: Optional[int] = None
|
| 129 |
+
source_grade: Optional[str] = None
|
| 130 |
+
rebuilt: Optional[bool] = None
|
| 131 |
+
note: str = ""
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
@dataclass
|
| 135 |
+
class YearResult:
|
| 136 |
+
codes: List[str]
|
| 137 |
+
names: List[str]
|
| 138 |
+
exact: bool # 只有一个代码,而且没有部分划转
|
| 139 |
+
steps: List[str] = field(default_factory=list)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class Gazetteer:
|
| 143 |
+
def __init__(self, data_dir=DATA, fuzzy=True, embedder=None, extra_rules=True, fuzzy_readings="main", fuzzy_min_len=3):
|
| 144 |
+
self.extra_rules = extra_rules
|
| 145 |
+
self.snap = defaultdict(dict)
|
| 146 |
+
with gzip.open(os.path.join(data_dir, "years.csv.gz"), "rt", encoding="utf-8") as fh:
|
| 147 |
+
for r in csv.DictReader(fh):
|
| 148 |
+
self.snap[int(r["year"])][r["code"]] = r["name"]
|
| 149 |
+
self.meta = {int(k): v for k, v in json.load(open(os.path.join(data_dir, "years_meta.json"), encoding="utf-8")).items()}
|
| 150 |
+
self.years = sorted(self.snap)
|
| 151 |
+
self.cur_year = self.years[-1]
|
| 152 |
+
self.changes = []
|
| 153 |
+
with gzip.open(os.path.join(data_dir, "changes.csv.gz"), "rt", encoding="utf-8") as fh:
|
| 154 |
+
self.changes = list(csv.DictReader(fh))
|
| 155 |
+
self.fwd = defaultdict(list) # (year, old) -> [row]
|
| 156 |
+
self.back = defaultdict(list) # (year, new) -> [row]
|
| 157 |
+
for r in self.changes:
|
| 158 |
+
y = int(r["year"])
|
| 159 |
+
if r["old_code"] and r["new_code"]:
|
| 160 |
+
self.fwd[(y, r["old_code"])].append(r)
|
| 161 |
+
self.back[(y, r["new_code"])].append(r)
|
| 162 |
+
self._full = {}
|
| 163 |
+
self._alias = {}
|
| 164 |
+
self.fuzzy = None
|
| 165 |
+
if fuzzy:
|
| 166 |
+
try:
|
| 167 |
+
from .fuzzy import Fuzzy
|
| 168 |
+
self.fuzzy = Fuzzy(data_dir, readings=fuzzy_readings, min_len=fuzzy_min_len)
|
| 169 |
+
except FileNotFoundError:
|
| 170 |
+
self.fuzzy = None
|
| 171 |
+
self.embedder = embedder
|
| 172 |
+
|
| 173 |
+
# ---------- 索引 ----------
|
| 174 |
+
def _index(self, y):
|
| 175 |
+
if y not in self._full:
|
| 176 |
+
full, al = defaultdict(set), defaultdict(set)
|
| 177 |
+
for c, n in self.snap[y].items():
|
| 178 |
+
full[n].add(c)
|
| 179 |
+
s = stem(n)
|
| 180 |
+
if s != n and len(s) >= 2: # 去掉通名后只剩 1 个字的不作简称(例:“市区”→“市”)
|
| 181 |
+
al[s].add(c)
|
| 182 |
+
for a in autonomy_aliases(n):
|
| 183 |
+
al[a].add(c)
|
| 184 |
+
if self.extra_rules:
|
| 185 |
+
for a in extra_aliases(n):
|
| 186 |
+
al[a].add(c)
|
| 187 |
+
self._full[y], self._alias[y] = full, al
|
| 188 |
+
return self._full[y], self._alias[y]
|
| 189 |
+
|
| 190 |
+
def table_year(self, year):
|
| 191 |
+
"""给定年份用哪一年的表:有就用那一年,没有就用之前最近的一年;晚于最新用最新。
|
| 192 |
+
早于第一年时返回第一年,但 align 和 to_year 在这种情况下不给代码(见各自的说明)。"""
|
| 193 |
+
if year is None:
|
| 194 |
+
return self.cur_year
|
| 195 |
+
year = int(year)
|
| 196 |
+
ys = [y for y in self.years if y <= year]
|
| 197 |
+
return ys[-1] if ys else self.years[0]
|
| 198 |
+
|
| 199 |
+
def parent_names(self, y, code):
|
| 200 |
+
out = []
|
| 201 |
+
T = self.snap[y]
|
| 202 |
+
if level(code) != "province":
|
| 203 |
+
out.append(T.get(code[:2] + "0000", ""))
|
| 204 |
+
if level(code) == "county" and code[:4] + "00" in T:
|
| 205 |
+
out.append(T[code[:4] + "00"])
|
| 206 |
+
return [n for n in out if n]
|
| 207 |
+
|
| 208 |
+
def _parent_ok(self, y, c, parent):
|
| 209 |
+
if not parent:
|
| 210 |
+
return True
|
| 211 |
+
p = parent
|
| 212 |
+
ps = stem(p) or p
|
| 213 |
+
names = self.parent_names(y, c)
|
| 214 |
+
for n in names:
|
| 215 |
+
if n == p or stem(n) == ps or n.startswith(ps) or ps.startswith(stem(n)) or p in autonomy_aliases(n):
|
| 216 |
+
return True
|
| 217 |
+
# 上级写成“省+市”时,逐段看
|
| 218 |
+
return any(stem(n) in p for n in names)
|
| 219 |
+
|
| 220 |
+
# ---------- 年份换算和沿革 ----------
|
| 221 |
+
def years_of(self, code):
|
| 222 |
+
return [y for y in self.years if code in self.snap[y]]
|
| 223 |
+
|
| 224 |
+
def to_year(self, code, year, from_year=None) -> YearResult:
|
| 225 |
+
"""把 code(某一年的代码)换成 year 年的代码。沿官方变更表走,不按名称猜。
|
| 226 |
+
拆分、合并会得到多个代码,这时 exact = False。"""
|
| 227 |
+
if year is not None and int(year) < self.years[0]:
|
| 228 |
+
return YearResult([], [], False, [f"数据只从 {self.years[0]} 年开始,不能换成 {year} 年的代码"])
|
| 229 |
+
ty = self.table_year(year)
|
| 230 |
+
ys = self.years_of(code)
|
| 231 |
+
if not ys:
|
| 232 |
+
return YearResult([], [], False, [f"{code} 不在任何一年的表里"])
|
| 233 |
+
fy = from_year if from_year in ys else (max([y for y in ys if y <= ty], default=min(ys)))
|
| 234 |
+
S, steps, exact = {code}, [], True
|
| 235 |
+
if fy <= ty:
|
| 236 |
+
path = [y for y in self.years if fy < y <= ty]
|
| 237 |
+
prev = fy
|
| 238 |
+
for b in path:
|
| 239 |
+
T = self.snap[b]
|
| 240 |
+
nS = set()
|
| 241 |
+
for c in S:
|
| 242 |
+
if c in T:
|
| 243 |
+
nS.add(c)
|
| 244 |
+
continue
|
| 245 |
+
rows = self.fwd.get((b, c), [])
|
| 246 |
+
whole = [r for r in rows if r["main"] == "是"]
|
| 247 |
+
use = whole or rows
|
| 248 |
+
if not use:
|
| 249 |
+
steps.append(f"{prev}→{b}:{c} 撤销,变更表里没有去向")
|
| 250 |
+
exact = False
|
| 251 |
+
continue
|
| 252 |
+
if len(use) > 1 or not whole:
|
| 253 |
+
exact = False
|
| 254 |
+
for r in use:
|
| 255 |
+
nS.add(r["new_code"])
|
| 256 |
+
steps.append(f"{prev}→{b}:{c} {r['old_name']} → {r['new_code']} {r['new_name']}({r['change_type']})")
|
| 257 |
+
for r in rows:
|
| 258 |
+
if r not in use:
|
| 259 |
+
steps.append(f"{prev}→{b}:{c} {r['old_name']} 的一部分划给 {r['new_code']} {r['new_name']}")
|
| 260 |
+
S, prev = nS, b
|
| 261 |
+
else:
|
| 262 |
+
path = [y for y in reversed(self.years) if ty <= y < fy]
|
| 263 |
+
nxt = fy
|
| 264 |
+
for a in path:
|
| 265 |
+
T = self.snap[a]
|
| 266 |
+
nS = set()
|
| 267 |
+
for c in S:
|
| 268 |
+
if c in T:
|
| 269 |
+
nS.add(c)
|
| 270 |
+
continue
|
| 271 |
+
rows = self.back.get((nxt, c), [])
|
| 272 |
+
if not rows:
|
| 273 |
+
steps.append(f"{a}←{nxt}:{c} 是新设的单位(公告写明设立,没有县级以上的前身),{a} 年没有对应的代码")
|
| 274 |
+
exact = False
|
| 275 |
+
continue
|
| 276 |
+
main = [r for r in rows if r["main"] == "是"]
|
| 277 |
+
use = main or rows
|
| 278 |
+
if len(use) > 1 or not main:
|
| 279 |
+
exact = False
|
| 280 |
+
for r in use:
|
| 281 |
+
nS.add(r["old_code"])
|
| 282 |
+
steps.append(f"{a}←{nxt}:{r['old_code']} {r['old_name']} → {c} {r['new_name']}({r['change_type']})")
|
| 283 |
+
S, nxt = nS, a
|
| 284 |
+
T = self.snap[ty]
|
| 285 |
+
codes = sorted(S)
|
| 286 |
+
exact = exact and len(codes) == 1
|
| 287 |
+
return YearResult(codes, [T.get(c, "") for c in codes], exact, steps)
|
| 288 |
+
|
| 289 |
+
def current(self, code):
|
| 290 |
+
r = self.to_year(code, self.cur_year)
|
| 291 |
+
return r.codes[0] if r.exact else None
|
| 292 |
+
|
| 293 |
+
def history(self, code):
|
| 294 |
+
"""一个代码的沿革:名称和年份段,加上涉及它的变更。"""
|
| 295 |
+
segs = []
|
| 296 |
+
for y in self.years:
|
| 297 |
+
n = self.snap[y].get(code)
|
| 298 |
+
if n and segs and segs[-1]["name"] == n and segs[-1]["to"] == self.years[self.years.index(y) - 1]:
|
| 299 |
+
segs[-1]["to"] = y
|
| 300 |
+
elif n:
|
| 301 |
+
segs.append(dict(name=n, **{"from": y, "to": y}))
|
| 302 |
+
ev = [dict(year=int(r["year"]), type=r["change_type"], relation=r["relation"], partial=r["partial"] == "是",
|
| 303 |
+
old_code=r["old_code"], old_name=r["old_name"], new_code=r["new_code"], new_name=r["new_name"],
|
| 304 |
+
basis=r["basis"], source_url=r["source_url"])
|
| 305 |
+
for r in self.changes if code in (r["old_code"], r["new_code"])]
|
| 306 |
+
return dict(code=code, names=segs, events=sorted(ev, key=lambda e: e["year"]))
|
| 307 |
+
|
| 308 |
+
# ---------- 地名 → 代码 ----------
|
| 309 |
+
def _find(self, y, text, parent):
|
| 310 |
+
full, al = self._index(y)
|
| 311 |
+
for tier, got in (("exact", full.get(text, set())), ("alias", al.get(text, set()))):
|
| 312 |
+
cs = {c for c in got if self._parent_ok(y, c, parent)}
|
| 313 |
+
if cs:
|
| 314 |
+
return tier, cs
|
| 315 |
+
return None, set()
|
| 316 |
+
|
| 317 |
+
def _is_name(self, s):
|
| 318 |
+
for y in (self.cur_year, self.years[0]):
|
| 319 |
+
full, al = self._index(y)
|
| 320 |
+
if s in full or s in al:
|
| 321 |
+
return True
|
| 322 |
+
return False
|
| 323 |
+
|
| 324 |
+
def _cands(self, y, codes):
|
| 325 |
+
return sorted([Candidate(c, self.snap[y].get(c, ""), level(c), "".join(self.parent_names(y, c))) for c in codes],
|
| 326 |
+
key=lambda x: (LV_ORDER[x.level], x.code))
|
| 327 |
+
|
| 328 |
+
def _lookup(self, text, parent, ty):
|
| 329 |
+
"""返回 (method, {代��}, 是否损失精度, 说明)。代码都是 ty 年的。"""
|
| 330 |
+
tier, cs = self._find(ty, text, parent)
|
| 331 |
+
if cs:
|
| 332 |
+
return tier, cs, False, ""
|
| 333 |
+
# 那一年的表里没有:到所有其他年份找,再沿变更表换成 ty 年的代码。
|
| 334 |
+
# 同一个写法在不同年份可能指不同单位(例:东市区在合肥和蚌埠都有过),所以不能只看最近的一年。
|
| 335 |
+
found = {} # code -> (年份, tier)
|
| 336 |
+
best_tier = None
|
| 337 |
+
for y in sorted(self.years, key=lambda v: (abs(v - ty), -v)):
|
| 338 |
+
if y == ty:
|
| 339 |
+
continue
|
| 340 |
+
tier, cs = self._find(y, text, parent)
|
| 341 |
+
if not cs:
|
| 342 |
+
continue
|
| 343 |
+
if best_tier is None:
|
| 344 |
+
best_tier = tier
|
| 345 |
+
if tier != best_tier and best_tier == "exact":
|
| 346 |
+
continue # 有全称对上的,就不要只是简称对上的
|
| 347 |
+
for c in cs:
|
| 348 |
+
found.setdefault(c, y)
|
| 349 |
+
if found:
|
| 350 |
+
out, exacts, notes = set(), [], []
|
| 351 |
+
for c, y in sorted(found.items(), key=lambda kv: -kv[1]):
|
| 352 |
+
r = self.to_year(c, ty, from_year=y)
|
| 353 |
+
out |= set(r.codes)
|
| 354 |
+
exacts.append(r.exact)
|
| 355 |
+
notes.append(f"{y} 年的 {c} {self.snap[y][c]}")
|
| 356 |
+
# 几条路走到同一个代码、而且至少一条路是确定的:不算损失精度
|
| 357 |
+
lossy = len(out) != 1 or not any(exacts)
|
| 358 |
+
return "history", out, lossy, "在 " + "、".join(notes[:5]) + " 找到,按变更表换成 " + str(ty) + " 年的代码。"
|
| 359 |
+
return None, set(), False, ""
|
| 360 |
+
|
| 361 |
+
def align(self, text, year=None, parent=None, use_fuzzy=True, use_embedding=True) -> Match:
|
| 362 |
+
q = normalize(text)
|
| 363 |
+
par = normalize(parent) or None
|
| 364 |
+
if par in NOT_PARENT:
|
| 365 |
+
par = None
|
| 366 |
+
ty = self.table_year(year)
|
| 367 |
+
note = ""
|
| 368 |
+
before = year is not None and int(year) < self.years[0]
|
| 369 |
+
if before:
|
| 370 |
+
note = f"数据只从 {self.years[0]} 年开始,没有 {year} 年的表。下面是按 {ty} 年的表找到的,只供参考,不给代码。"
|
| 371 |
+
elif year is not None and int(year) != ty:
|
| 372 |
+
note = f"{year} 年没有表,用 {ty} 年的表。"
|
| 373 |
+
meta = self.meta.get(ty, {})
|
| 374 |
+
generic = q in GENERIC or stem(q) in GENERIC
|
| 375 |
+
|
| 376 |
+
def parent_settles(codes):
|
| 377 |
+
"""给了上级,而且上级把候选缩到 1 个,这个候选确实在这个上级下面。"""
|
| 378 |
+
if not par or len(codes) != 1:
|
| 379 |
+
return False
|
| 380 |
+
c = next(iter(codes))
|
| 381 |
+
ups = {c[:4] + "00", c[:2] + "0000"} - {c}
|
| 382 |
+
T = self.snap[ty]
|
| 383 |
+
return any(u in T and (normalize(T[u]) == par or stem(T[u]) == stem(par)) for u in ups)
|
| 384 |
+
|
| 385 |
+
def done(method, codes, conf, extra=""):
|
| 386 |
+
if generic and parent_settles(codes):
|
| 387 |
+
pass # 例:上级“长治市”+“城区”是一个确定的单位
|
| 388 |
+
elif (before or generic) and conf in ("high", "medium"):
|
| 389 |
+
conf = "low"
|
| 390 |
+
if generic and not before:
|
| 391 |
+
extra = f"“{q}”通常是泛称。" + extra
|
| 392 |
+
cands = self._cands(ty, codes)
|
| 393 |
+
best = cands[0].code if cands else None
|
| 394 |
+
code = best if conf in ("high", "medium") else None
|
| 395 |
+
nm = self.snap[ty].get(best) if best else None
|
| 396 |
+
return Match(text, code, nm, best, conf, method, cands, ty, meta.get("source_grade"), meta.get("rebuilt"),
|
| 397 |
+
(note + extra).strip())
|
| 398 |
+
|
| 399 |
+
if not q:
|
| 400 |
+
return done("none", set(), "none", "输入是空的。")
|
| 401 |
+
method, cs, lossy, why = self._lookup(q, par, ty)
|
| 402 |
+
if cs:
|
| 403 |
+
if len(cs) == 1 and not lossy:
|
| 404 |
+
return done(method, cs, "high" if method == "exact" else "medium", why)
|
| 405 |
+
extra = why + ("有多个候选。" if len(cs) > 1 else "") + ("经过拆分或合并,换算不唯一。" if lossy else "")
|
| 406 |
+
return done(method, cs, "low", extra)
|
| 407 |
+
# 上级和本级连写:天水市麦积区、湖北省武汉市
|
| 408 |
+
if len(q) >= 4:
|
| 409 |
+
for k in range(len(q) - 2, 1, -1):
|
| 410 |
+
head, tail = q[:k], q[k:]
|
| 411 |
+
if self._is_name(head):
|
| 412 |
+
m2, cs2, lossy2, why2 = self._lookup(tail, head, ty)
|
| 413 |
+
if cs2:
|
| 414 |
+
conf = "medium" if (len(cs2) == 1 and not lossy2) else "low"
|
| 415 |
+
return done("split", cs2, conf, f"按“{head}”+“{tail}”拆开。" + why2)
|
| 416 |
+
# 给了上级而对不上:去掉上级再查
|
| 417 |
+
if par:
|
| 418 |
+
m3, cs3, lossy3, why3 = self._lookup(q, None, ty)
|
| 419 |
+
if cs3:
|
| 420 |
+
return done("no_parent", cs3, "low", f"上级“{par}”对不上,去掉上级找到。" + why3)
|
| 421 |
+
if use_fuzzy and self.fuzzy:
|
| 422 |
+
cs4, why4 = self.fuzzy.match(self, q, par, ty)
|
| 423 |
+
if cs4:
|
| 424 |
+
return done("fuzzy", cs4, "low", why4)
|
| 425 |
+
if use_embedding and self.embedder:
|
| 426 |
+
cs5, why5 = self.embedder.match(self, q, par, ty)
|
| 427 |
+
if cs5:
|
| 428 |
+
return done("embedding", cs5, "low", why5)
|
| 429 |
+
return done("none", set(), "none", "查不到。")
|
geoalign/geoalign/data/changes.csv.gz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b9fb1cb887fa6078fe612df5798f7d658a594575791f5262c686b3b014c15516
|
| 3 |
+
size 6904
|
geoalign/geoalign/data/confusion.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
geoalign/geoalign/data/years.csv.gz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:38254922b5dedae02768cf2c78ad76e5181065ade6f456fb50e17ca75f927a13
|
| 3 |
+
size 332029
|
geoalign/geoalign/data/years_meta.json
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"2012": {
|
| 3 |
+
"source_grade": "A",
|
| 4 |
+
"rebuilt": false,
|
| 5 |
+
"source_url": "http://files2.mca.gov.cn/cws/201308/20130821143408921.htm",
|
| 6 |
+
"archive_url": "http://web.archive.org/web/20141001020151id_/http://files2.mca.gov.cn/cws/201308/20130821143408921.htm",
|
| 7 |
+
"fetched": "2026-11-18"
|
| 8 |
+
},
|
| 9 |
+
"2013": {
|
| 10 |
+
"source_grade": "A",
|
| 11 |
+
"rebuilt": false,
|
| 12 |
+
"source_url": "http://files2.mca.gov.cn/cws/201404/20140404125552372.htm",
|
| 13 |
+
"archive_url": "http://web.archive.org/web/20141001053611id_/http://files2.mca.gov.cn/cws/201404/20140404125552372.htm",
|
| 14 |
+
"fetched": "2026-11-18"
|
| 15 |
+
},
|
| 16 |
+
"2014": {
|
| 17 |
+
"source_grade": "A",
|
| 18 |
+
"rebuilt": false,
|
| 19 |
+
"source_url": "http://files2.mca.gov.cn/cws/201502/20150225163817214.html",
|
| 20 |
+
"archive_url": "http://web.archive.org/web/20150402113603id_/http://files2.mca.gov.cn/cws/201502/20150225163817214.html",
|
| 21 |
+
"fetched": "2026-11-18"
|
| 22 |
+
},
|
| 23 |
+
"2015": {
|
| 24 |
+
"source_grade": "A",
|
| 25 |
+
"rebuilt": false,
|
| 26 |
+
"source_url": "https://www.mca.gov.cn/mzsj/tjbz/a/2015/up/201602/20160200880229.htm",
|
| 27 |
+
"archive_url": "",
|
| 28 |
+
"fetched": "2026-11-18"
|
| 29 |
+
},
|
| 30 |
+
"2016": {
|
| 31 |
+
"source_grade": "A",
|
| 32 |
+
"rebuilt": false,
|
| 33 |
+
"source_url": "https://www.mca.gov.cn/mzsj/tjbz/a/2016/201702/201702231133.html",
|
| 34 |
+
"archive_url": "",
|
| 35 |
+
"fetched": "2026-11-18"
|
| 36 |
+
},
|
| 37 |
+
"2017": {
|
| 38 |
+
"source_grade": "A",
|
| 39 |
+
"rebuilt": false,
|
| 40 |
+
"source_url": "https://www.mca.gov.cn/mzsj/tjbz/a/2018/201803131439.html",
|
| 41 |
+
"archive_url": "",
|
| 42 |
+
"fetched": "2026-11-18"
|
| 43 |
+
},
|
| 44 |
+
"2018": {
|
| 45 |
+
"source_grade": "A",
|
| 46 |
+
"rebuilt": false,
|
| 47 |
+
"source_url": "https://www.mca.gov.cn/mzsj/xzqh/1980/201903/201903011447.html",
|
| 48 |
+
"archive_url": "",
|
| 49 |
+
"fetched": "2026-11-18"
|
| 50 |
+
},
|
| 51 |
+
"2019": {
|
| 52 |
+
"source_grade": "A",
|
| 53 |
+
"rebuilt": false,
|
| 54 |
+
"source_url": "https://www.mca.gov.cn/mzsj/xzqh/1980/2019/202002281436.html",
|
| 55 |
+
"archive_url": "",
|
| 56 |
+
"fetched": "2026-11-18"
|
| 57 |
+
},
|
| 58 |
+
"2020": {
|
| 59 |
+
"source_grade": "A",
|
| 60 |
+
"rebuilt": false,
|
| 61 |
+
"source_url": "https://www.mca.gov.cn/mzsj/xzqh/2020/20201201.html",
|
| 62 |
+
"archive_url": "",
|
| 63 |
+
"fetched": "2026-11-18"
|
| 64 |
+
},
|
| 65 |
+
"2021": {
|
| 66 |
+
"source_grade": "A",
|
| 67 |
+
"rebuilt": false,
|
| 68 |
+
"source_url": "https://www.mca.gov.cn/mzsj/xzqh/2021/20211201.html",
|
| 69 |
+
"archive_url": "",
|
| 70 |
+
"fetched": "2026-11-18"
|
| 71 |
+
},
|
| 72 |
+
"2022": {
|
| 73 |
+
"source_grade": "A",
|
| 74 |
+
"rebuilt": false,
|
| 75 |
+
"source_url": "https://www.mca.gov.cn/mzsj/xzqh/2022/202201xzqh.html",
|
| 76 |
+
"archive_url": "",
|
| 77 |
+
"fetched": "2026-11-18"
|
| 78 |
+
},
|
| 79 |
+
"2023": {
|
| 80 |
+
"source_grade": "A",
|
| 81 |
+
"rebuilt": false,
|
| 82 |
+
"source_url": "https://www.mca.gov.cn/mzsj/xzqh/2023/202301xzqh.html",
|
| 83 |
+
"archive_url": "",
|
| 84 |
+
"fetched": "2026-11-18"
|
| 85 |
+
},
|
| 86 |
+
"2024": {
|
| 87 |
+
"source_grade": "A",
|
| 88 |
+
"rebuilt": false,
|
| 89 |
+
"source_url": "https://www.mca.gov.cn/mzsj/xzqh/2025/202401xzqh.html",
|
| 90 |
+
"archive_url": "",
|
| 91 |
+
"fetched": "2026-11-18"
|
| 92 |
+
},
|
| 93 |
+
"2025": {
|
| 94 |
+
"source_grade": "A",
|
| 95 |
+
"rebuilt": false,
|
| 96 |
+
"source_url": "https://dmfw.mca.gov.cn/XzqhVersionPublish.html",
|
| 97 |
+
"archive_url": "",
|
| 98 |
+
"fetched": "2026-11-18"
|
| 99 |
+
}
|
| 100 |
+
}
|
geoalign/geoalign/embed.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""向量模型后备(可选)。查表和错别字规则都找不到时才用。要装 sentence-transformers 和 torch。
|
| 2 |
+
|
| 3 |
+
用法:
|
| 4 |
+
from geoalign.core import Gazetteer
|
| 5 |
+
from geoalign.embed import Embedder
|
| 6 |
+
g = Gazetteer()
|
| 7 |
+
g.embedder = Embedder(g, "/path/to/bge-m3")
|
| 8 |
+
g.align("某个写法")
|
| 9 |
+
|
| 10 |
+
条目库:每个(代码,名称)连续出现的一段算一条。条目文字是“上级名称 + 名称(起年—止年)”,现行的写“(现行)”。
|
| 11 |
+
查询文字是“上级 + 写法”,给了年份时加“,某年”。取最相近的一条,再按变更表换成要的那一年的代码。
|
| 12 |
+
"""
|
| 13 |
+
import os
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def entries(g):
|
| 17 |
+
out = []
|
| 18 |
+
for code in sorted({c for y in g.years for c in g.snap[y]}):
|
| 19 |
+
for seg in g.history(code)["names"]:
|
| 20 |
+
y1 = seg["to"]
|
| 21 |
+
span = "现行" if y1 == g.cur_year else f"{seg['from']}—{y1}年"
|
| 22 |
+
par = "".join(g.parent_names(y1, code))
|
| 23 |
+
out.append(dict(code=code, name=seg["name"], y0=seg["from"], y1=y1, text=f"{par}{seg['name']}({span})"))
|
| 24 |
+
return out
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
QUERY_PREFIX = {"bge-small-zh": "为这个句子生成表示以用于检索相关文章:", "bge-large-zh": "为这个句子生成表示以用于检索相关文章:"}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class Embedder:
|
| 31 |
+
def __init__(self, g, model_path, device="cpu", cache_dir=None, batch_size=64, prefix=None):
|
| 32 |
+
from sentence_transformers import SentenceTransformer
|
| 33 |
+
self.model = SentenceTransformer(model_path, device=device)
|
| 34 |
+
self.prefix = prefix if prefix is not None else next((v for k, v in QUERY_PREFIX.items() if k in model_path), "")
|
| 35 |
+
self.E = entries(g)
|
| 36 |
+
cache = os.path.join(cache_dir, os.path.basename(model_path.rstrip("/")) + ".entries.npy") if cache_dir else None
|
| 37 |
+
import numpy as np
|
| 38 |
+
if cache and os.path.exists(cache):
|
| 39 |
+
self.M = np.load(cache)
|
| 40 |
+
else:
|
| 41 |
+
self.M = self.model.encode([e["text"] for e in self.E], batch_size=batch_size, normalize_embeddings=True,
|
| 42 |
+
show_progress_bar=False, convert_to_numpy=True)
|
| 43 |
+
if cache:
|
| 44 |
+
np.save(cache, self.M)
|
| 45 |
+
|
| 46 |
+
def query_text(self, q, parent=None, year=None):
|
| 47 |
+
s = (parent or "") + q
|
| 48 |
+
if year:
|
| 49 |
+
s += f",{year}年"
|
| 50 |
+
return self.prefix + s
|
| 51 |
+
|
| 52 |
+
def nearest(self, texts, k=1):
|
| 53 |
+
import numpy as np
|
| 54 |
+
V = self.model.encode(texts, batch_size=64, normalize_embeddings=True, show_progress_bar=False, convert_to_numpy=True)
|
| 55 |
+
S = V @ self.M.T
|
| 56 |
+
idx = np.argsort(-S, axis=1)[:, :k]
|
| 57 |
+
return [[(self.E[j], float(S[i, j])) for j in row] for i, row in enumerate(idx)]
|
| 58 |
+
|
| 59 |
+
def match(self, g, q, parent, ty, year=None):
|
| 60 |
+
(e, s), = self.nearest([self.query_text(q, parent, year if year is not None else (ty if ty != g.cur_year else None))])[0]
|
| 61 |
+
r = g.to_year(e["code"], ty)
|
| 62 |
+
if not r.codes:
|
| 63 |
+
return set(), ""
|
| 64 |
+
return set(r.codes[:1]), f"向量模型:最像“{e['text']}”(相似度 {s:.3f})。"
|
geoalign/geoalign/fuzzy.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""错别字规则。查表找不到时才用。只用标准库,字表在 data/confusion.json(由 tools/build_confusion.py 生成)。
|
| 2 |
+
|
| 3 |
+
规则按顺序:
|
| 4 |
+
1. 通名写错:去掉通名以后和某个单位的简称相同(涟水区 → 涟水县,盱眙市 → 盱眙县)。
|
| 5 |
+
2. 一个字写错:和某个单位的全称或简称只差 1 个字,而且这个字是同音字(不计声调)或形近字(字表里最像的 5 个)。
|
| 6 |
+
3. 给了上级时,只在上级下面找。找不到时去掉上级再找一次。
|
| 7 |
+
(规则 2 允许通名位置写成同音字、规则 3 的“去掉上级再找”,这两条是看过 88 道真实错别字题的错误以后加的,成绩分开报。)
|
| 8 |
+
候选不止一个时,全部返回,由调用方看。结果的把握一律是 low。
|
| 9 |
+
"""
|
| 10 |
+
import json, os
|
| 11 |
+
|
| 12 |
+
from .core import stem, autonomy_aliases, extra_aliases, normalize # noqa: F401
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class Fuzzy:
|
| 16 |
+
def __init__(self, data_dir, readings="main", min_len=3):
|
| 17 |
+
"""readings:main = 多音字只用最常见的读音;all = 用全部读音。
|
| 18 |
+
min_len:参加“一个字写错”比较的写法最少几个字(2 个字的简称错一个字就是错一半)。"""
|
| 19 |
+
d = json.load(open(os.path.join(data_dir, "confusion.json"), encoding="utf-8"))
|
| 20 |
+
if readings == "all":
|
| 21 |
+
self.py = {k: set(v) for k, v in d["pinyin"].items()}
|
| 22 |
+
else:
|
| 23 |
+
self.py = {k: {v} for k, v in d["pinyin_main"].items()}
|
| 24 |
+
self.min_len = min_len
|
| 25 |
+
self.readings = readings
|
| 26 |
+
self.shape = {k: set(v) for k, v in d["shape"].items()}
|
| 27 |
+
self._keys = {}
|
| 28 |
+
|
| 29 |
+
def similar(self, typed, real):
|
| 30 |
+
"""typed 是不是 real 的同音字或形近字。"""
|
| 31 |
+
if typed == real:
|
| 32 |
+
return True
|
| 33 |
+
if self.py.get(typed, set()) & self.py.get(real, set()):
|
| 34 |
+
return True
|
| 35 |
+
return typed in self.shape.get(real, ()) or real in self.shape.get(typed, ())
|
| 36 |
+
|
| 37 |
+
def _keys_for(self, g, y):
|
| 38 |
+
"""y 年每个单位的全称、简称。按长度分组,比较时只比同样长的。"""
|
| 39 |
+
if y not in self._keys:
|
| 40 |
+
by_len = {}
|
| 41 |
+
for c, n in g.snap[y].items():
|
| 42 |
+
forms = {n, stem(n)} | set(autonomy_aliases(n))
|
| 43 |
+
if g.extra_rules:
|
| 44 |
+
forms |= set(extra_aliases(n))
|
| 45 |
+
for f in forms:
|
| 46 |
+
if len(f) >= 2:
|
| 47 |
+
by_len.setdefault(len(f), []).append((f, c, f == n))
|
| 48 |
+
self._keys[y] = by_len
|
| 49 |
+
return self._keys[y]
|
| 50 |
+
|
| 51 |
+
def match(self, g, q, parent, y):
|
| 52 |
+
_, al = g._index(y)
|
| 53 |
+
# 1. 通名写错
|
| 54 |
+
s = stem(q)
|
| 55 |
+
if s != q and len(s) >= 2:
|
| 56 |
+
cs = {c for c in al.get(s, set()) | g._index(y)[0].get(s, set()) if g._parent_ok(y, c, parent)}
|
| 57 |
+
if cs:
|
| 58 |
+
return cs, f"通名写错:按“{s}”找到。"
|
| 59 |
+
# 2. 一个字写错。查询也去掉通名再比一次(墉桥区 → 墉桥 对 埇桥)
|
| 60 |
+
found = {}
|
| 61 |
+
for qq in {q, s}:
|
| 62 |
+
if len(qq) < self.min_len:
|
| 63 |
+
continue
|
| 64 |
+
for f, c, is_full in self._keys_for(g, y).get(len(qq), []):
|
| 65 |
+
diff = [i for i in range(len(qq)) if qq[i] != f[i]]
|
| 66 |
+
if len(diff) != 1:
|
| 67 |
+
continue
|
| 68 |
+
i = diff[0]
|
| 69 |
+
# 通名写成同音字(高青线 → 高青县)也算。区、县、市互换不是同音,由规则 1 管
|
| 70 |
+
if self.similar(qq[i], f[i]) and g._parent_ok(y, c, parent):
|
| 71 |
+
found.setdefault(c, f"“{qq[i]}”是“{f[i]}”的错字({f})")
|
| 72 |
+
if found:
|
| 73 |
+
return set(found), "一个字写错:" + ";".join(sorted(set(found.values()))[:5]) + "。"
|
| 74 |
+
# 给了上级而找不到:去掉上级再试一次(上级列有时填的是本级自己)
|
| 75 |
+
if parent:
|
| 76 |
+
cs, why = self.match(g, q, None, y)
|
| 77 |
+
if cs:
|
| 78 |
+
return cs, f"上级“{parent}”对不上,去掉上级后:" + why
|
| 79 |
+
return set(), ""
|
geoalign/pyproject.toml
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["setuptools>=61"]
|
| 3 |
+
build-backend = "setuptools.build_meta"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "geoalign"
|
| 7 |
+
version = "0.1.0"
|
| 8 |
+
description = "把中国县级以上行政区划的名称对到官方代码,并在 2012 至 2025 年之间换算代码"
|
| 9 |
+
readme = "README.md"
|
| 10 |
+
license = {text = "Apache-2.0"}
|
| 11 |
+
requires-python = ">=3.8"
|
| 12 |
+
dependencies = []
|
| 13 |
+
classifiers = [
|
| 14 |
+
"License :: OSI Approved :: Apache Software License",
|
| 15 |
+
"Programming Language :: Python :: 3",
|
| 16 |
+
"Natural Language :: Chinese (Simplified)",
|
| 17 |
+
]
|
| 18 |
+
|
| 19 |
+
[project.optional-dependencies]
|
| 20 |
+
embed = ["sentence-transformers", "torch"]
|
| 21 |
+
|
| 22 |
+
[tool.setuptools]
|
| 23 |
+
packages = ["geoalign"]
|
| 24 |
+
|
| 25 |
+
[tool.setuptools.package-data]
|
| 26 |
+
geoalign = ["data/*"]
|
geoalign/tests/test_geoalign.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""geoalign 的测试。只用标准库:python -m unittest discover -s tests"""
|
| 2 |
+
import csv, gzip, json, os, sys, unittest
|
| 3 |
+
|
| 4 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 5 |
+
from geoalign.core import Gazetteer, stem, normalize, extra_aliases, autonomy_aliases, DATA # noqa: E402
|
| 6 |
+
|
| 7 |
+
G = Gazetteer()
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class TestScope(unittest.TestCase):
|
| 11 |
+
"""发布包里只有发布范围内的数据。"""
|
| 12 |
+
|
| 13 |
+
def test_years_from_2012(self):
|
| 14 |
+
with gzip.open(os.path.join(DATA, "years.csv.gz"), "rt", encoding="utf-8") as fh:
|
| 15 |
+
years = {int(r["year"]) for r in csv.DictReader(fh)}
|
| 16 |
+
self.assertEqual(min(years), 2012)
|
| 17 |
+
self.assertEqual(max(years), 2025)
|
| 18 |
+
|
| 19 |
+
def test_changes_from_2013(self):
|
| 20 |
+
with gzip.open(os.path.join(DATA, "changes.csv.gz"), "rt", encoding="utf-8") as fh:
|
| 21 |
+
ys = {int(r["year"]) for r in csv.DictReader(fh)}
|
| 22 |
+
self.assertGreaterEqual(min(ys), 2013)
|
| 23 |
+
|
| 24 |
+
def test_all_grade_a(self):
|
| 25 |
+
meta = json.load(open(os.path.join(DATA, "years_meta.json"), encoding="utf-8"))
|
| 26 |
+
self.assertEqual({m["source_grade"] for m in meta.values()}, {"A"})
|
| 27 |
+
self.assertFalse(any(m["rebuilt"] for m in meta.values()))
|
| 28 |
+
|
| 29 |
+
def test_2025_is_year_end(self):
|
| 30 |
+
# 岑岭县、草湖市是 2026 年公告设立的,不在 2025 年底的表里
|
| 31 |
+
self.assertNotIn("653132", G.snap[2025])
|
| 32 |
+
self.assertNotIn("659013", G.snap[2025])
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class TestNames(unittest.TestCase):
|
| 36 |
+
def test_stem(self):
|
| 37 |
+
self.assertEqual(stem("荆州市"), "荆州")
|
| 38 |
+
self.assertEqual(stem("杏花岭区"), "杏花岭")
|
| 39 |
+
self.assertEqual(stem("神农架林区"), "神农架")
|
| 40 |
+
|
| 41 |
+
def test_aliases(self):
|
| 42 |
+
self.assertIn("凉山", autonomy_aliases("凉山彝族自治州"))
|
| 43 |
+
self.assertIn("融水县", autonomy_aliases("融水苗族自治县"))
|
| 44 |
+
self.assertIn("科右前旗", extra_aliases("科尔沁右翼前旗"))
|
| 45 |
+
self.assertIn("顺河区", extra_aliases("顺河回族区"))
|
| 46 |
+
|
| 47 |
+
def test_normalize(self):
|
| 48 |
+
self.assertEqual(normalize(" 洛阳。 "), "洛阳")
|
| 49 |
+
self.assertEqual(normalize("锦江 "), "锦江")
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class TestAlign(unittest.TestCase):
|
| 53 |
+
def test_exact_current(self):
|
| 54 |
+
m = G.align("密云区")
|
| 55 |
+
self.assertEqual((m.code, m.confidence, m.method), ("110118", "high", "exact"))
|
| 56 |
+
self.assertEqual(m.source_grade, "A")
|
| 57 |
+
self.assertFalse(m.rebuilt)
|
| 58 |
+
|
| 59 |
+
def test_old_name_to_current(self):
|
| 60 |
+
m = G.align("密云县") # 2015 年撤县设区
|
| 61 |
+
self.assertEqual(m.code, "110118")
|
| 62 |
+
self.assertEqual(m.method, "history")
|
| 63 |
+
|
| 64 |
+
def test_year(self):
|
| 65 |
+
m = G.align("密云县", year=2013)
|
| 66 |
+
self.assertEqual(m.code, "110228")
|
| 67 |
+
self.assertEqual(m.year, 2013)
|
| 68 |
+
|
| 69 |
+
def test_year_before_data_gives_no_code(self):
|
| 70 |
+
m = G.align("密云县", year=1990)
|
| 71 |
+
self.assertIsNone(m.code)
|
| 72 |
+
self.assertIn(m.confidence, ("low", "none"))
|
| 73 |
+
self.assertIn("2012", m.note)
|
| 74 |
+
|
| 75 |
+
def test_homonym_without_context_returns_all(self):
|
| 76 |
+
m = G.align("朝阳区")
|
| 77 |
+
self.assertIsNone(m.code)
|
| 78 |
+
self.assertEqual(m.confidence, "low")
|
| 79 |
+
self.assertGreaterEqual(len(m.candidates), 2)
|
| 80 |
+
self.assertIn("220104", [c.code for c in m.candidates])
|
| 81 |
+
|
| 82 |
+
def test_homonym_with_parent(self):
|
| 83 |
+
self.assertEqual(G.align("朝阳区", parent="长春市").code, "220104")
|
| 84 |
+
self.assertEqual(G.align("朝阳区", parent="北京").code, "110105")
|
| 85 |
+
|
| 86 |
+
def test_cross_level_ambiguity(self):
|
| 87 |
+
m = G.align("吉林")
|
| 88 |
+
self.assertIsNone(m.code)
|
| 89 |
+
self.assertEqual({c.code for c in m.candidates}, {"220000", "220200"})
|
| 90 |
+
|
| 91 |
+
def test_short_name(self):
|
| 92 |
+
self.assertEqual(G.align("凉山州").code, "513400")
|
| 93 |
+
self.assertEqual(G.align("襄阳").code, "420600")
|
| 94 |
+
|
| 95 |
+
def test_generic_names_not_confident(self):
|
| 96 |
+
for q in ("市", "新区", "城区", "郊区", "矿区", "东区", "西区"):
|
| 97 |
+
self.assertIsNone(G.align(q).code, q)
|
| 98 |
+
self.assertEqual(G.align("东区", parent="攀枝花市").code, "510402") # 上级确定成一个单位时照常给
|
| 99 |
+
|
| 100 |
+
def test_concatenated_parent(self):
|
| 101 |
+
m = G.align("天水市麦积区")
|
| 102 |
+
self.assertEqual((m.code, m.method), ("620503", "split"))
|
| 103 |
+
|
| 104 |
+
def test_not_found(self):
|
| 105 |
+
m = G.align("不存在的地方")
|
| 106 |
+
self.assertIsNone(m.code)
|
| 107 |
+
self.assertEqual(m.confidence, "none")
|
| 108 |
+
|
| 109 |
+
def test_garbage_parent_ignored(self):
|
| 110 |
+
self.assertEqual(G.align("密云区", parent="市辖区").code, "110118")
|
| 111 |
+
|
| 112 |
+
def test_typo_is_low_confidence(self):
|
| 113 |
+
m = G.align("候马市")
|
| 114 |
+
self.assertIsNone(m.code)
|
| 115 |
+
self.assertEqual(m.best, "141081")
|
| 116 |
+
self.assertEqual((m.method, m.confidence), ("fuzzy", "low"))
|
| 117 |
+
|
| 118 |
+
def test_typo_wrong_suffix(self):
|
| 119 |
+
m = G.align("盱眙市")
|
| 120 |
+
self.assertEqual(m.best, "320830")
|
| 121 |
+
self.assertEqual(m.method, "fuzzy")
|
| 122 |
+
|
| 123 |
+
def test_merged_old_name(self):
|
| 124 |
+
self.assertEqual(G.align("下城区").code, "330105") # 2021 年并入拱墅区
|
| 125 |
+
|
| 126 |
+
def test_split_main_successor(self):
|
| 127 |
+
self.assertEqual(G.align("绍兴县").code, "330603") # 2013 年撤县设柯桥区
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class TestToYear(unittest.TestCase):
|
| 131 |
+
def test_forward(self):
|
| 132 |
+
r = G.to_year("110228", 2025)
|
| 133 |
+
self.assertEqual((r.codes, r.exact), (["110118"], True))
|
| 134 |
+
|
| 135 |
+
def test_backward(self):
|
| 136 |
+
r = G.to_year("110118", 2013)
|
| 137 |
+
self.assertEqual(r.codes, ["110228"])
|
| 138 |
+
|
| 139 |
+
def test_before_data(self):
|
| 140 |
+
r = G.to_year("110118", 2000)
|
| 141 |
+
self.assertEqual(r.codes, [])
|
| 142 |
+
self.assertFalse(r.exact)
|
| 143 |
+
|
| 144 |
+
def test_split_reports_side_transfer(self):
|
| 145 |
+
r = G.to_year("330621", 2014)
|
| 146 |
+
self.assertEqual(r.codes, ["330603"])
|
| 147 |
+
self.assertTrue(any("一部分划给 330602" in s for s in r.steps))
|
| 148 |
+
|
| 149 |
+
def test_backward_from_new_unit(self):
|
| 150 |
+
r = G.to_year("440310", 2015) # 坪山区 2016 年从龙岗区划出
|
| 151 |
+
self.assertEqual(r.codes, ["440307"])
|
| 152 |
+
self.assertFalse(r.exact)
|
| 153 |
+
|
| 154 |
+
def test_merge_many_to_one_backward(self):
|
| 155 |
+
r = G.to_year("500157", 2024) # 两江新区 ← 江北区、渝北区
|
| 156 |
+
self.assertIn("500105", r.codes)
|
| 157 |
+
self.assertIn("500112", r.codes)
|
| 158 |
+
self.assertFalse(r.exact)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class TestCorrections(unittest.TestCase):
|
| 162 |
+
"""逐条重读公告以后改正的行(改正清单:dataset/data/corrections_applied.csv)。"""
|
| 163 |
+
|
| 164 |
+
def test_split_without_main_returns_all(self):
|
| 165 |
+
r = G.to_year("130103", 2016) # 石家庄桥东区 2014 年撤销,分给长安区、桥西区
|
| 166 |
+
self.assertEqual(r.codes, ["130102", "130104"])
|
| 167 |
+
self.assertFalse(r.exact)
|
| 168 |
+
|
| 169 |
+
def test_merge_into_new(self):
|
| 170 |
+
self.assertEqual(G.to_year("140402", 2019).codes, ["140403"]) # 长治城区 → 潞州区
|
| 171 |
+
self.assertEqual(G.to_year("360105", 2020).codes, ["360112"]) # 湾里区 → 新建区
|
| 172 |
+
|
| 173 |
+
def test_level_change_same_name(self):
|
| 174 |
+
r = G.to_year("469003", 2016) # 县级儋州市 → 地级儋州市
|
| 175 |
+
self.assertEqual((r.codes, r.exact), (["460400"], True))
|
| 176 |
+
|
| 177 |
+
def test_code_change_not_split(self):
|
| 178 |
+
r = G.to_year("542430", 2018) # 尼玛县换代码,不是 2012 年的拆分
|
| 179 |
+
self.assertEqual((r.codes, r.exact), (["540629"], True))
|
| 180 |
+
|
| 181 |
+
def test_table_lag_row_kept(self):
|
| 182 |
+
self.assertEqual(G.to_year("130604", 2018).codes, ["130606"]) # 南市区:代码表 2017 年才去掉
|
| 183 |
+
|
| 184 |
+
def test_split_main_unknown(self):
|
| 185 |
+
r = G.to_year("130521", 2025) # 邢台县 2020 年撤销,分给襄都区、信都区,公告没说主要承继
|
| 186 |
+
self.assertEqual(r.codes, ["130502", "130503"])
|
| 187 |
+
self.assertFalse(r.exact)
|
| 188 |
+
|
| 189 |
+
def test_event_recorded_once(self):
|
| 190 |
+
self.assertEqual(len(G.history("130604")["events"]), 1) # 南市区并入莲池区只记一次
|
| 191 |
+
|
| 192 |
+
def test_new_unit_step_message(self):
|
| 193 |
+
r = G.to_year("460202", 2012) # 三亚海棠区 2014 年由乡镇设立
|
| 194 |
+
self.assertEqual(r.codes, [])
|
| 195 |
+
self.assertIn("新设", r.steps[-1])
|
| 196 |
+
self.assertNotIn("未查明", r.steps[-1])
|
| 197 |
+
|
| 198 |
+
def test_continuing_unit_not_main(self):
|
| 199 |
+
r = G.to_year("330113", 2020) # 临平区由余杭区的一部分设立,余杭区继续存在
|
| 200 |
+
self.assertEqual(r.codes, ["330110"])
|
| 201 |
+
self.assertFalse(r.exact)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
class TestHistory(unittest.TestCase):
|
| 205 |
+
def test_names(self):
|
| 206 |
+
h = G.history("330105")
|
| 207 |
+
self.assertIn("拱墅区", [s["name"] for s in h["names"]])
|
| 208 |
+
self.assertTrue(h["events"])
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
if __name__ == "__main__":
|
| 212 |
+
unittest.main()
|
geoalign/tools/build_confusion.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""错别字规则用的字表。写到 geoalign/data/confusion.json。
|
| 2 |
+
用法:python tools/build_confusion.py <数据集 data 目录里的 years.csv> <字体文件 NotoSansCJK-Regular.ttc>
|
| 3 |
+
只在建表时用 Pillow、numpy、pypinyin;工具库运行时不用它们。
|
| 4 |
+
|
| 5 |
+
两种“像”:
|
| 6 |
+
1. 同音:不计声调的拼音有相同的(多音字算所有读音)。字的范围:GBK 里的全部汉字 + 官方名称里的字。
|
| 7 |
+
2. 形近:用 Noto Sans CJK SC 把字画成 56×56 的图,模糊 1.5 像素,算余弦相似度。
|
| 8 |
+
每个官方名称里的字,取最像的 5 个字,相似度至少 0.80。
|
| 9 |
+
参数(5 个、0.80、模糊 1.5)是先定的,没有按测试题调。
|
| 10 |
+
"""
|
| 11 |
+
import csv, json, os, sys
|
| 12 |
+
import numpy as np
|
| 13 |
+
from PIL import Image, ImageDraw, ImageFont, ImageFilter
|
| 14 |
+
from pypinyin import pinyin, Style
|
| 15 |
+
|
| 16 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 17 |
+
PKG = os.path.join(os.path.dirname(HERE), "geoalign")
|
| 18 |
+
YEARS, FONT = sys.argv[1], sys.argv[2]
|
| 19 |
+
TOPK, MINSIM, BLUR, SZ = 5, 0.80, 1.5, 56
|
| 20 |
+
|
| 21 |
+
name_chars = set()
|
| 22 |
+
for r in csv.DictReader(open(YEARS, encoding="utf-8")):
|
| 23 |
+
name_chars |= {ch for ch in r["name"] if "一" <= ch <= "鿿" or "㐀" <= ch <= "䶿"}
|
| 24 |
+
pool = set(name_chars)
|
| 25 |
+
for hi in range(0x81, 0xFF):
|
| 26 |
+
for lo in range(0x40, 0xFF):
|
| 27 |
+
try:
|
| 28 |
+
ch = bytes([hi, lo]).decode("gbk")
|
| 29 |
+
except UnicodeDecodeError:
|
| 30 |
+
continue
|
| 31 |
+
if "一" <= ch <= "鿿":
|
| 32 |
+
pool.add(ch)
|
| 33 |
+
pool = sorted(pool)
|
| 34 |
+
print("name chars", len(name_chars), "pool", len(pool))
|
| 35 |
+
|
| 36 |
+
# 拼音
|
| 37 |
+
py = {}
|
| 38 |
+
for ch in pool:
|
| 39 |
+
ps = {p.rstrip("0123456789") for p in pinyin(ch, style=Style.NORMAL, heteronym=True)[0]}
|
| 40 |
+
ps = {p for p in ps if p.isalpha() and p.isascii()}
|
| 41 |
+
if ps:
|
| 42 |
+
py[ch] = sorted(ps)
|
| 43 |
+
py_main = {}
|
| 44 |
+
for ch in pool:
|
| 45 |
+
p = pinyin(ch, style=Style.NORMAL, heteronym=False)[0][0]
|
| 46 |
+
if p.isalpha() and p.isascii():
|
| 47 |
+
py_main[ch] = p
|
| 48 |
+
|
| 49 |
+
# 字形
|
| 50 |
+
# Noto Sans CJK 的 ttc 里第几个是简体中文
|
| 51 |
+
idx = next(i for i in range(10) if "SC" in ImageFont.truetype(FONT, 12, index=i).getname()[0])
|
| 52 |
+
F = ImageFont.truetype(FONT, 48, index=idx)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def vec(ch):
|
| 56 |
+
im = Image.new("L", (SZ, SZ), 0)
|
| 57 |
+
ImageDraw.Draw(im).text((4, -6), ch, font=F, fill=255)
|
| 58 |
+
im = im.filter(ImageFilter.GaussianBlur(BLUR))
|
| 59 |
+
return np.asarray(im, dtype=np.float32).ravel()
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
tofu = vec("\U000F0000") # 字体里没有的字画出来的样子
|
| 63 |
+
V = np.stack([vec(ch) for ch in pool])
|
| 64 |
+
has = ~np.all(np.isclose(V, tofu[None, :]), axis=1) & (V.sum(1) > 0)
|
| 65 |
+
V /= np.linalg.norm(V, axis=1, keepdims=True) + 1e-6
|
| 66 |
+
print("chars without glyph", int((~has).sum()))
|
| 67 |
+
P = {ch: i for i, ch in enumerate(pool)}
|
| 68 |
+
shape = {}
|
| 69 |
+
nc = sorted(name_chars)
|
| 70 |
+
for k in range(0, len(nc), 500):
|
| 71 |
+
chunk = [c for c in nc[k:k + 500]]
|
| 72 |
+
ids = [P[c] for c in chunk]
|
| 73 |
+
S = V[ids] @ V.T
|
| 74 |
+
S[:, ~has] = -1
|
| 75 |
+
for row, c in zip(S, chunk):
|
| 76 |
+
if not has[P[c]]:
|
| 77 |
+
continue
|
| 78 |
+
row[P[c]] = -1
|
| 79 |
+
top = np.argsort(-row)[:TOPK]
|
| 80 |
+
nb = [pool[j] for j in top if row[j] >= MINSIM]
|
| 81 |
+
if nb:
|
| 82 |
+
shape[c] = nb
|
| 83 |
+
json.dump(dict(params=dict(topk=TOPK, minsim=MINSIM, blur=BLUR, size=SZ, font="Noto Sans CJK SC"), pinyin=py, pinyin_main=py_main, shape=shape),
|
| 84 |
+
open(os.path.join(PKG, "data", "confusion.json"), "w", encoding="utf-8"), ensure_ascii=False)
|
| 85 |
+
print("pinyin", len(py), "shape", len(shape))
|
| 86 |
+
for c in "埇浉硚瀍亳汨谯楞侯淞颍丘州德惠凤藏梁新芦":
|
| 87 |
+
print(c, shape.get(c), py.get(c))
|