kenya-abbreviations 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,97 @@
1
+ Metadata-Version: 2.4
2
+ Name: kenya-abbreviations
3
+ Version: 0.1.0
4
+ Summary: Identify abbreviations of Kenyan counties, constituencies, sub-counties and former districts.
5
+ License-Expression: MIT
6
+ Classifier: Programming Language :: Python :: 3
7
+ Classifier: Operating System :: OS Independent
8
+ Requires-Python: >=3.9
9
+ Description-Content-Type: text/markdown
10
+ Provides-Extra: dev
11
+ Requires-Dist: pytest>=7; extra == "dev"
12
+
13
+ # kenya-abbreviations
14
+
15
+ Identify abbreviations of Kenyan **counties**, **constituencies**, **sub-counties** and former **districts**. No dependencies; Python 3.9+.
16
+
17
+ ```python
18
+ from kenya_abbreviations import expand, identify, abbreviate
19
+
20
+ expand("Msa") # 'Mombasa'
21
+ expand("Kisumu E", kinds="constituency") # 'Kisumu East'
22
+ expand("N. Imenti", kinds="constituency") # 'North Imenti'
23
+ expand("Imenti N", kinds="district") # 'Imenti North'
24
+ expand("KCN") # 'Kitutu Chache North'
25
+ expand("Emb. East", kinds="district") # 'Embu East'
26
+ expand("Kibera") # 'Kibra'
27
+
28
+ for m in identify("Kisumu E"):
29
+ print(m)
30
+ # Kisumu East (constituency, Kisumu) [238] score=0.94 via abbreviation ('Kisumu East')
31
+ # Kisumu East (subcounty, Kisumu) [238] score=0.94 via abbreviation ('Kisumu East')
32
+ # Kisumu East (district, Nyanza) score=0.94 via abbreviation ('Kisumu East')
33
+
34
+ abbreviate("Kisumu East") # 'KSM E'
35
+ ```
36
+
37
+ ## Install
38
+
39
+ ```
40
+ pip install -e . # or: pip install -e ".[dev]" for pytest
41
+ ```
42
+
43
+ ## API
44
+
45
+ | Function | Purpose |
46
+ |---|---|
47
+ | `identify(query, kinds=None, county=None, limit=10, min_score=0.6)` | All candidate places for an abbreviation, best first, as `Match` objects (`place`, `score`, `matched`, `method`). |
48
+ | `best_match(query, ...)` | The top `Match`, or `None`. |
49
+ | `expand(query, ...)` | The top match's official name, or `None`. |
50
+ | `abbreviate(name)` | Short form of a name: the curated one if there is one (`MSA`, `NBI`, `KSM`, `NKR`, `UG`), otherwise generated. |
51
+ | `counties()`, `constituencies(county=None)`, `subcounties(county=None)`, `districts(province=None)` | List the reference data. |
52
+ | `get(code, kind="constituency")` | Look up by official code, e.g. `get(290)` gives Mathare and `get(47, "county")` gives Nairobi. |
53
+
54
+ `kinds` takes `"county"`, `"constituency"`, `"subcounty"`, `"district"`, a `Kind` value, or a list of these. `county=` narrows results to one county, and you can abbreviate the county name too (`county="Msa"`).
55
+
56
+ ### Command line
57
+
58
+ ```
59
+ kenya-abbr Msa
60
+ kenya-abbr "Kisumu E" --kind constituency
61
+ kenya-abbr Central --county Kisumu
62
+ kenya-abbr --abbreviate Kitutu Chache North
63
+ python -m kenya_abbreviations KCN
64
+ ```
65
+
66
+ ## How matching works
67
+
68
+ Kenya has no official abbreviation standard for these units, so the matcher recognises the ways people usually shorten names:
69
+
70
+ - **Shortened words:** each query word must start with the same letter as a name word, and its letters must appear in that word in order. Examples: `Msa` → Mombasa, `Twn` → Town, `E` → East.
71
+ - **One token per word:** `Kisumu E`, `Dagoretti N`, `Nkr Twn W`.
72
+ - **Several words squashed into one token:** `KCN` → Kitutu Chache North, `Homabay` → Homa Bay.
73
+ - **Words in a different order:** `Imenti N` → North Imenti. These score slightly lower.
74
+ - **Only some of the words:** `Chuka` → Chuka/Igambang'ombe. These score lower.
75
+ - **Misspellings:** `Kisumo` → Kisumu.
76
+ - **Ignored when matching:** case, apostrophes (`Murang'a` = `Muranga`), punctuation, `Mount`/`Mt.`, and unit words such as *County*, *Sub-County*, *Constituency* and *District*.
77
+
78
+ Exact names score 1.0 and curated aliases score 0.99. If two matches score the same, counties come first, then constituencies, then sub-counties, then districts.
79
+
80
+ Abbreviations are often ambiguous. For example, `Emb E` can mean Embu East (a district) or Embakasi East (a constituency). Use `identify()` to see all the candidates, or pass `kinds=` or `county=` to narrow them down.
81
+
82
+ ## Data and sources
83
+
84
+ | Kind | Count | Source |
85
+ |---|---|---|
86
+ | Counties | 47 | Constitution of Kenya 2010, First Schedule (codes 001–047), with former province |
87
+ | Constituencies | 290 | IEBC, 2012 boundaries (codes 001–290) |
88
+ | Sub-counties | 290 | County sub-counties. Under County Governments Act 2012, s.48(1)(a), these correspond to the constituencies and share their codes. |
89
+ | Districts | 208 | Government of Kenya district list, July 2009 (via Wikipedia, *Sub-counties of Kenya*), with former province. The source says this list is incomplete. |
90
+
91
+ Not included yet: the national-government administrative sub-counties (about 314 as of 2023), which differ from the constituencies in some counties. To add them or more aliases, edit `src/kenya_abbreviations/_data.py`.
92
+
93
+ ## Development
94
+
95
+ ```
96
+ python -m pytest --doctest-modules src tests
97
+ ```
@@ -0,0 +1,85 @@
1
+ # kenya-abbreviations
2
+
3
+ Identify abbreviations of Kenyan **counties**, **constituencies**, **sub-counties** and former **districts**. No dependencies; Python 3.9+.
4
+
5
+ ```python
6
+ from kenya_abbreviations import expand, identify, abbreviate
7
+
8
+ expand("Msa") # 'Mombasa'
9
+ expand("Kisumu E", kinds="constituency") # 'Kisumu East'
10
+ expand("N. Imenti", kinds="constituency") # 'North Imenti'
11
+ expand("Imenti N", kinds="district") # 'Imenti North'
12
+ expand("KCN") # 'Kitutu Chache North'
13
+ expand("Emb. East", kinds="district") # 'Embu East'
14
+ expand("Kibera") # 'Kibra'
15
+
16
+ for m in identify("Kisumu E"):
17
+ print(m)
18
+ # Kisumu East (constituency, Kisumu) [238] score=0.94 via abbreviation ('Kisumu East')
19
+ # Kisumu East (subcounty, Kisumu) [238] score=0.94 via abbreviation ('Kisumu East')
20
+ # Kisumu East (district, Nyanza) score=0.94 via abbreviation ('Kisumu East')
21
+
22
+ abbreviate("Kisumu East") # 'KSM E'
23
+ ```
24
+
25
+ ## Install
26
+
27
+ ```
28
+ pip install -e . # or: pip install -e ".[dev]" for pytest
29
+ ```
30
+
31
+ ## API
32
+
33
+ | Function | Purpose |
34
+ |---|---|
35
+ | `identify(query, kinds=None, county=None, limit=10, min_score=0.6)` | All candidate places for an abbreviation, best first, as `Match` objects (`place`, `score`, `matched`, `method`). |
36
+ | `best_match(query, ...)` | The top `Match`, or `None`. |
37
+ | `expand(query, ...)` | The top match's official name, or `None`. |
38
+ | `abbreviate(name)` | Short form of a name: the curated one if there is one (`MSA`, `NBI`, `KSM`, `NKR`, `UG`), otherwise generated. |
39
+ | `counties()`, `constituencies(county=None)`, `subcounties(county=None)`, `districts(province=None)` | List the reference data. |
40
+ | `get(code, kind="constituency")` | Look up by official code, e.g. `get(290)` gives Mathare and `get(47, "county")` gives Nairobi. |
41
+
42
+ `kinds` takes `"county"`, `"constituency"`, `"subcounty"`, `"district"`, a `Kind` value, or a list of these. `county=` narrows results to one county, and you can abbreviate the county name too (`county="Msa"`).
43
+
44
+ ### Command line
45
+
46
+ ```
47
+ kenya-abbr Msa
48
+ kenya-abbr "Kisumu E" --kind constituency
49
+ kenya-abbr Central --county Kisumu
50
+ kenya-abbr --abbreviate Kitutu Chache North
51
+ python -m kenya_abbreviations KCN
52
+ ```
53
+
54
+ ## How matching works
55
+
56
+ Kenya has no official abbreviation standard for these units, so the matcher recognises the ways people usually shorten names:
57
+
58
+ - **Shortened words:** each query word must start with the same letter as a name word, and its letters must appear in that word in order. Examples: `Msa` → Mombasa, `Twn` → Town, `E` → East.
59
+ - **One token per word:** `Kisumu E`, `Dagoretti N`, `Nkr Twn W`.
60
+ - **Several words squashed into one token:** `KCN` → Kitutu Chache North, `Homabay` → Homa Bay.
61
+ - **Words in a different order:** `Imenti N` → North Imenti. These score slightly lower.
62
+ - **Only some of the words:** `Chuka` → Chuka/Igambang'ombe. These score lower.
63
+ - **Misspellings:** `Kisumo` → Kisumu.
64
+ - **Ignored when matching:** case, apostrophes (`Murang'a` = `Muranga`), punctuation, `Mount`/`Mt.`, and unit words such as *County*, *Sub-County*, *Constituency* and *District*.
65
+
66
+ Exact names score 1.0 and curated aliases score 0.99. If two matches score the same, counties come first, then constituencies, then sub-counties, then districts.
67
+
68
+ Abbreviations are often ambiguous. For example, `Emb E` can mean Embu East (a district) or Embakasi East (a constituency). Use `identify()` to see all the candidates, or pass `kinds=` or `county=` to narrow them down.
69
+
70
+ ## Data and sources
71
+
72
+ | Kind | Count | Source |
73
+ |---|---|---|
74
+ | Counties | 47 | Constitution of Kenya 2010, First Schedule (codes 001–047), with former province |
75
+ | Constituencies | 290 | IEBC, 2012 boundaries (codes 001–290) |
76
+ | Sub-counties | 290 | County sub-counties. Under County Governments Act 2012, s.48(1)(a), these correspond to the constituencies and share their codes. |
77
+ | Districts | 208 | Government of Kenya district list, July 2009 (via Wikipedia, *Sub-counties of Kenya*), with former province. The source says this list is incomplete. |
78
+
79
+ Not included yet: the national-government administrative sub-counties (about 314 as of 2023), which differ from the constituencies in some counties. To add them or more aliases, edit `src/kenya_abbreviations/_data.py`.
80
+
81
+ ## Development
82
+
83
+ ```
84
+ python -m pytest --doctest-modules src tests
85
+ ```
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "kenya-abbreviations"
7
+ version = "0.1.0"
8
+ description = "Identify abbreviations of Kenyan counties, constituencies, sub-counties and former districts."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ dependencies = []
13
+ classifiers = [
14
+ "Programming Language :: Python :: 3",
15
+ "Operating System :: OS Independent",
16
+ ]
17
+
18
+ [project.optional-dependencies]
19
+ dev = ["pytest>=7"]
20
+
21
+ [project.scripts]
22
+ kenya-abbr = "kenya_abbreviations.cli:main"
23
+
24
+ [tool.setuptools.packages.find]
25
+ where = ["src"]
26
+
27
+ [tool.setuptools.package-data]
28
+ kenya_abbreviations = ["py.typed"]
29
+
30
+ [tool.pytest.ini_options]
31
+ testpaths = ["tests"]
32
+ pythonpath = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,43 @@
1
+ """Identify abbreviations of Kenyan counties, constituencies, sub-counties
2
+ and former districts.
3
+
4
+ >>> from kenya_abbreviations import expand, identify
5
+ >>> expand("Msa")
6
+ 'Mombasa'
7
+ >>> expand("Kisumu E", kinds="constituency")
8
+ 'Kisumu East'
9
+ >>> identify("N. Imenti")[0].place.name
10
+ 'North Imenti'
11
+ """
12
+
13
+ from .models import Kind, Match, Place
14
+ from .registry import (
15
+ abbreviate,
16
+ best_match,
17
+ constituencies,
18
+ counties,
19
+ districts,
20
+ expand,
21
+ get,
22
+ identify,
23
+ places,
24
+ subcounties,
25
+ )
26
+
27
+ __all__ = [
28
+ "Kind",
29
+ "Match",
30
+ "Place",
31
+ "abbreviate",
32
+ "best_match",
33
+ "constituencies",
34
+ "counties",
35
+ "districts",
36
+ "expand",
37
+ "get",
38
+ "identify",
39
+ "places",
40
+ "subcounties",
41
+ ]
42
+
43
+ __version__ = "0.1.0"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,235 @@
1
+ """Reference data: counties, constituencies (= county sub-counties) and
2
+ former districts of Kenya.
3
+
4
+ Sources:
5
+ * Counties and county codes: First Schedule of the Constitution of Kenya
6
+ (2010), codes 001-047.
7
+ * Constituencies and IEBC codes 001-290: IEBC (2012 boundaries review,
8
+ as used in the 2013, 2017 and 2022 general elections). Codes are
9
+ assigned in the order listed below, county by county.
10
+ * Sub-counties: under section 48(1)(a) of the County Governments Act,
11
+ 2012, the county decentralised sub-county units correspond to the
12
+ constituencies, so the sub-county list is the constituency list.
13
+ * Districts: list of districts as published by the Government of Kenya
14
+ in July 2009 (208 districts; reproduced on Wikipedia's "Sub-counties
15
+ of Kenya" page, which notes the list is incomplete). Three apparent
16
+ typos on that page were corrected: Kanyanya -> Kenyenya,
17
+ Mirangini -> Mirangine, Bunyula -> Bunyala.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from typing import Dict, List, Tuple
23
+
24
+ COAST = "Coast"
25
+ NORTH_EASTERN = "North Eastern"
26
+ EASTERN = "Eastern"
27
+ CENTRAL = "Central"
28
+ RIFT_VALLEY = "Rift Valley"
29
+ WESTERN = "Western"
30
+ NYANZA = "Nyanza"
31
+ NAIROBI = "Nairobi"
32
+
33
+ # (code, name, former province, aliases/common abbreviations)
34
+ COUNTIES: List[Tuple[str, str, str, Tuple[str, ...]]] = [
35
+ ("001", "Mombasa", COAST, ("MSA",)),
36
+ ("002", "Kwale", COAST, ()),
37
+ ("003", "Kilifi", COAST, ()),
38
+ ("004", "Tana River", COAST, ()),
39
+ ("005", "Lamu", COAST, ()),
40
+ ("006", "Taita-Taveta", COAST, ()),
41
+ ("007", "Garissa", NORTH_EASTERN, ()),
42
+ ("008", "Wajir", NORTH_EASTERN, ()),
43
+ ("009", "Mandera", NORTH_EASTERN, ()),
44
+ ("010", "Marsabit", EASTERN, ()),
45
+ ("011", "Isiolo", EASTERN, ()),
46
+ ("012", "Meru", EASTERN, ()),
47
+ ("013", "Tharaka-Nithi", EASTERN, ()),
48
+ ("014", "Embu", EASTERN, ()),
49
+ ("015", "Kitui", EASTERN, ()),
50
+ ("016", "Machakos", EASTERN, ()),
51
+ ("017", "Makueni", EASTERN, ()),
52
+ ("018", "Nyandarua", CENTRAL, ()),
53
+ ("019", "Nyeri", CENTRAL, ()),
54
+ ("020", "Kirinyaga", CENTRAL, ()),
55
+ ("021", "Murang'a", CENTRAL, ()),
56
+ ("022", "Kiambu", CENTRAL, ()),
57
+ ("023", "Turkana", RIFT_VALLEY, ()),
58
+ ("024", "West Pokot", RIFT_VALLEY, ()),
59
+ ("025", "Samburu", RIFT_VALLEY, ()),
60
+ ("026", "Trans Nzoia", RIFT_VALLEY, ()),
61
+ ("027", "Uasin Gishu", RIFT_VALLEY, ("UG",)),
62
+ ("028", "Elgeyo-Marakwet", RIFT_VALLEY, ()),
63
+ ("029", "Nandi", RIFT_VALLEY, ()),
64
+ ("030", "Baringo", RIFT_VALLEY, ()),
65
+ ("031", "Laikipia", RIFT_VALLEY, ()),
66
+ ("032", "Nakuru", RIFT_VALLEY, ("NKR", "NKU")),
67
+ ("033", "Narok", RIFT_VALLEY, ()),
68
+ ("034", "Kajiado", RIFT_VALLEY, ()),
69
+ ("035", "Kericho", RIFT_VALLEY, ()),
70
+ ("036", "Bomet", RIFT_VALLEY, ()),
71
+ ("037", "Kakamega", WESTERN, ()),
72
+ ("038", "Vihiga", WESTERN, ()),
73
+ ("039", "Bungoma", WESTERN, ()),
74
+ ("040", "Busia", WESTERN, ()),
75
+ ("041", "Siaya", NYANZA, ()),
76
+ ("042", "Kisumu", NYANZA, ("KSM",)),
77
+ ("043", "Homa Bay", NYANZA, ()),
78
+ ("044", "Migori", NYANZA, ()),
79
+ ("045", "Kisii", NYANZA, ()),
80
+ ("046", "Nyamira", NYANZA, ()),
81
+ ("047", "Nairobi", NAIROBI, ("NBI", "NRB", "Nairobi City")),
82
+ ]
83
+
84
+ # County code -> constituencies in IEBC code order. An entry is either a
85
+ # name or (name, aliases).
86
+ CONSTITUENCIES: Dict[str, list] = {
87
+ "001": ["Changamwe", "Jomvu", "Kisauni", "Nyali", "Likoni", "Mvita"],
88
+ "002": ["Msambweni", "Lunga Lunga", "Matuga", "Kinango"],
89
+ "003": ["Kilifi North", "Kilifi South", "Kaloleni", "Rabai", "Ganze",
90
+ "Malindi", "Magarini"],
91
+ "004": ["Garsen", "Galole", "Bura"],
92
+ "005": ["Lamu East", "Lamu West"],
93
+ "006": ["Taveta", "Wundanyi", "Mwatate", "Voi"],
94
+ "007": [("Garissa Township", ("Garissa Town",)), "Balambala", "Lagdera",
95
+ "Dadaab", "Fafi", "Ijara"],
96
+ "008": ["Wajir North", "Wajir East", "Tarbaj", "Wajir West", "Eldas",
97
+ "Wajir South"],
98
+ "009": ["Mandera West", "Banissa", "Mandera North", "Mandera South",
99
+ "Mandera East", "Lafey"],
100
+ "010": ["Moyale", "North Horr", "Saku", "Laisamis"],
101
+ "011": ["Isiolo North", "Isiolo South"],
102
+ "012": ["Igembe South", "Igembe Central", "Igembe North", "Tigania West",
103
+ "Tigania East", "North Imenti", "Buuri", "Central Imenti",
104
+ "South Imenti"],
105
+ "013": ["Maara", ("Chuka/Igambang'ombe", ("Chuka", "Igambang'ombe")),
106
+ "Tharaka"],
107
+ "014": ["Manyatta", "Runyenjes", "Mbeere South", "Mbeere North"],
108
+ "015": ["Mwingi North", "Mwingi West", "Mwingi Central", "Kitui West",
109
+ "Kitui Rural", "Kitui Central", "Kitui East", "Kitui South"],
110
+ "016": ["Masinga", "Yatta", "Kangundo", "Matungulu", "Kathiani", "Mavoko",
111
+ "Machakos Town", "Mwala"],
112
+ "017": ["Mbooni", "Kilome", "Kaiti", "Makueni", "Kibwezi West",
113
+ "Kibwezi East"],
114
+ "018": ["Kinangop", "Kipipiri", ("Ol Kalou", ("Olkalou",)),
115
+ ("Ol Joro Orok", ("Ol Jorok", "Oljoro Orok")), "Ndaragwa"],
116
+ "019": ["Tetu", "Kieni", "Mathira", "Othaya", "Mukurweini", "Nyeri Town"],
117
+ "020": ["Mwea", "Gichugu", "Ndia", "Kirinyaga Central"],
118
+ "021": ["Kangema", "Mathioya", "Kiharu", "Kigumo", "Maragwa", "Kandara",
119
+ "Gatanga"],
120
+ "022": ["Gatundu South", "Gatundu North", "Juja", "Thika Town", "Ruiru",
121
+ "Githunguri", "Kiambu", "Kiambaa", "Kabete", "Kikuyu", "Limuru",
122
+ "Lari"],
123
+ "023": ["Turkana North", "Turkana West", "Turkana Central", "Loima",
124
+ "Turkana South", "Turkana East"],
125
+ "024": ["Kapenguria", "Sigor", "Kacheliba", "Pokot South"],
126
+ "025": ["Samburu West", "Samburu North", "Samburu East"],
127
+ "026": ["Kwanza", "Endebess", "Saboti", "Kiminini", "Cherangany"],
128
+ "027": ["Soy", "Turbo", "Moiben", "Ainabkoi", "Kapseret", "Kesses"],
129
+ "028": ["Marakwet East", "Marakwet West", "Keiyo North", "Keiyo South"],
130
+ "029": ["Tinderet", "Aldai", "Nandi Hills", "Chesumei", "Emgwen", "Mosop"],
131
+ "030": [("Tiaty", ("East Pokot",)), "Baringo North", "Baringo Central",
132
+ "Baringo South", "Mogotio", "Eldama Ravine"],
133
+ "031": ["Laikipia West", "Laikipia East", "Laikipia North"],
134
+ "032": ["Molo", "Njoro", "Naivasha", "Gilgil", "Kuresoi South",
135
+ "Kuresoi North", "Subukia", "Rongai", "Bahati", "Nakuru Town West",
136
+ "Nakuru Town East"],
137
+ "033": ["Kilgoris", "Emurua Dikirr", "Narok North", "Narok East",
138
+ "Narok South", "Narok West"],
139
+ "034": ["Kajiado North", "Kajiado Central", "Kajiado East",
140
+ "Kajiado West", "Kajiado South"],
141
+ "035": ["Kipkelion East", "Kipkelion West", "Ainamoi", "Bureti", "Belgut",
142
+ ("Sigowet/Soin", ("Sigowet", "Soin"))],
143
+ "036": ["Sotik", "Chepalungu", "Bomet East", "Bomet Central", "Konoin"],
144
+ "037": ["Lugari", "Likuyani", "Malava", "Lurambi", "Navakholo",
145
+ "Mumias West", "Mumias East", "Matungu", "Butere", "Khwisero",
146
+ "Shinyalu", "Ikolomani"],
147
+ "038": ["Vihiga", "Sabatia", "Hamisi", "Luanda", "Emuhaya"],
148
+ "039": [("Mt. Elgon", ("Mount Elgon",)), "Sirisia", "Kabuchai", "Bumula",
149
+ "Kanduyi", "Webuye East", "Webuye West", "Kimilili", "Tongaren"],
150
+ "040": ["Teso North", "Teso South", "Nambale", "Matayos", "Butula",
151
+ "Funyula", "Budalangi"],
152
+ "041": ["Ugenya", "Ugunja", "Alego Usonga", "Gem", "Bondo", "Rarieda"],
153
+ "042": ["Kisumu East", "Kisumu West", "Kisumu Central", "Seme", "Nyando",
154
+ "Muhoroni", "Nyakach"],
155
+ "043": ["Kasipul", "Kabondo Kasipul", "Karachuonyo", "Rangwe",
156
+ "Homa Bay Town", "Ndhiwa", "Suba North", "Suba South"],
157
+ "044": ["Rongo", "Awendo", "Suna East", "Suna West", "Uriri", "Nyatike",
158
+ "Kuria West", "Kuria East"],
159
+ "045": ["Bonchari", "South Mugirango", "Bomachoge Borabu", "Bobasi",
160
+ "Bomachoge Chache", "Nyaribari Masaba", "Nyaribari Chache",
161
+ "Kitutu Chache North", "Kitutu Chache South"],
162
+ "046": ["Kitutu Masaba", "West Mugirango", "North Mugirango", "Borabu"],
163
+ "047": ["Westlands", "Dagoretti North", "Dagoretti South",
164
+ ("Langata", ("Lang'ata",)), ("Kibra", ("Kibera",)), "Roysambu",
165
+ "Kasarani", "Ruaraka", "Embakasi South", "Embakasi North",
166
+ "Embakasi Central", "Embakasi East", "Embakasi West", "Makadara",
167
+ "Kamukunji", "Starehe", "Mathare"],
168
+ }
169
+
170
+ # Former province -> districts (Government of Kenya list, July 2009).
171
+ DISTRICTS: Dict[str, List[str]] = {
172
+ CENTRAL: [
173
+ "Gatanga", "Gatundu", "Githunguri", "Kabete", "Kandara", "Kiambaa",
174
+ "Kiambu East", "Kiambu West", "Kieni West", "Kieni East", "Kigumo",
175
+ "Kipipiri", "Kirinyaga Central", "Kirinyaga East", "Kirinyaga South",
176
+ "Kirinyaga West", "Lari", "Mirangine", "Mukurweini", "Muranga East",
177
+ "Muranga South", "Nyandarua Central", "Nyandarua North",
178
+ "Nyandarua South", "Nyandarua West", "Nyeri Central", "Nyeri East",
179
+ "Nyeri South", "Ruiru", "Thika East", "Thika West",
180
+ ],
181
+ COAST: [
182
+ "Kaloleni", "Kilifi", "Kilindini", "Kinango", "Kwale", "Lamu",
183
+ "Malindi", "Mombasa", "Msabweni", "Taita", "Tana Delta", "Tana River",
184
+ "Taveta",
185
+ ],
186
+ EASTERN: [
187
+ "Buuri", "Embu East", "Embu West", "Garbatula", "Igembe North",
188
+ "Igembe South", "Imenti North", "Imenti South", "Isiolo", "Kangundo",
189
+ "Kathiani", "Kathonzweni", "Kibwezi", "Kilungu", "Kitui Central",
190
+ "Kitui West", "Kyuso", "Maara", "Machakos", "Makueni", "Marsabit",
191
+ "Marsabit North", "Marsabit South", "Masinga", "Matungulu",
192
+ "Mbeere North", "Mbeere South", "Mbooni East", "Mbooni West",
193
+ "Meru Central", "Meru South", "Moyale", "Mukaa", "Mutitu", "Mutomo",
194
+ "Mwala", "Mwingi", "Nzaui", "Tharaka North", "Tharaka South",
195
+ "Tigania East", "Tigania West", "Yatta",
196
+ ],
197
+ NAIROBI: [
198
+ "Nairobi East", "Nairobi North", "Nairobi West", "Westlands",
199
+ ],
200
+ NORTH_EASTERN: [
201
+ "Fafi", "Garissa", "Ijara", "Lagdera", "Mandera Central",
202
+ "Mandera East", "Mandera North", "Mandera West", "Wajir East",
203
+ "Wajir North", "Wajir South", "Wajir West",
204
+ ],
205
+ NYANZA: [
206
+ "Bondo", "Borabu", "Gucha", "Homa Bay", "Kenyenya", "Kisii Central",
207
+ "Kisii South", "Kisumu East", "Kisumu West", "Kuria East",
208
+ "Kuria West", "Manga", "Marani", "Masaba", "Mbita", "Migori",
209
+ "Ndhiwa", "North Masaba", "Nyakach", "Nyamache", "Nyamira",
210
+ "Nyamira North", "Nyando", "Nyatike", "Rachuonyo North",
211
+ "Rachuonyo South", "Rarieda", "Rongo", "Siaya", "South Gucha", "Suba",
212
+ "Uriri",
213
+ ],
214
+ RIFT_VALLEY: [
215
+ "Baringo Central", "Baringo North", "Bomet", "Buret", "East Pokot",
216
+ "Eldoret East", "Eldoret West", "Kajiado North", "Kajiado South",
217
+ "Keiyo", "Kericho", "Kipkelion", "Koibatek", "Kwanza",
218
+ "Laikipia Central", "Laikipia East", "Laikipia North",
219
+ "Laikipia West", "Loima", "Loitoktok", "Marakwet", "Marigat",
220
+ "Mogotio", "Molo", "Naivasha", "Nakuru", "Nakuru North",
221
+ "Nandi Central", "Nandi East", "Nandi North", "Nandi South",
222
+ "Narok North", "Narok South", "Njoro", "North Pokot", "Nyahururu",
223
+ "Pokot Central", "Samburu Central", "Samburu East", "Samburu North",
224
+ "Sotik", "Tinderet", "Trans Nzoia East", "Trans Nzoia West",
225
+ "Trans Mara", "Turkana Central", "Turkana East", "Turkana North",
226
+ "Turkana South", "Turkana West", "Wareng", "West Pokot",
227
+ ],
228
+ WESTERN: [
229
+ "Bungoma Central", "Bungoma East", "Bungoma North", "Bungoma South",
230
+ "Bungoma West", "Bunyala", "Busia", "Butere", "Emuhaya", "Hamisi",
231
+ "Kakamega Central", "Kakamega East", "Kakamega North",
232
+ "Kakamega South", "Lugari", ("Mt. Elgon", ("Mount Elgon",)), "Mumias",
233
+ "Samia", "Teso North", "Teso South", "Vihiga",
234
+ ],
235
+ }
@@ -0,0 +1,46 @@
1
+ """Command line: ``kenya-abbr QUERY`` or ``python -m kenya_abbreviations QUERY``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from typing import List, Optional
8
+
9
+ from .models import Kind
10
+ from .registry import abbreviate, identify
11
+
12
+
13
+ def main(argv: Optional[List[str]] = None) -> int:
14
+ parser = argparse.ArgumentParser(
15
+ prog="kenya-abbr",
16
+ description="Identify Kenyan county/constituency/sub-county/district abbreviations.",
17
+ )
18
+ parser.add_argument("query", nargs="+", help="abbreviation or name, e.g. Msa, 'Kisumu E'")
19
+ parser.add_argument(
20
+ "-k", "--kind", action="append", choices=[k.value for k in Kind],
21
+ help="restrict to a kind (repeatable)",
22
+ )
23
+ parser.add_argument("-c", "--county", help="restrict to a county")
24
+ parser.add_argument("-n", "--limit", type=int, default=10)
25
+ parser.add_argument(
26
+ "-a", "--abbreviate", action="store_true",
27
+ help="print the abbreviation of a full name instead",
28
+ )
29
+ args = parser.parse_args(argv)
30
+ query = " ".join(args.query)
31
+
32
+ if args.abbreviate:
33
+ print(abbreviate(query))
34
+ return 0
35
+
36
+ matches = identify(query, kinds=args.kind, county=args.county, limit=args.limit)
37
+ if not matches:
38
+ print(f"No match for {query!r}", file=sys.stderr)
39
+ return 1
40
+ for m in matches:
41
+ print(m)
42
+ return 0
43
+
44
+
45
+ if __name__ == "__main__":
46
+ raise SystemExit(main())
@@ -0,0 +1,119 @@
1
+ """Scoring an abbreviation against a place name.
2
+
3
+ An abbreviation token ``a`` *abbreviates* a word ``w`` when they share the
4
+ first letter and the letters of ``a`` appear in ``w`` in order
5
+ ("msa" -> "mombasa", "ctrl" -> "central", "e" -> "east").
6
+
7
+ A query may use one token per word ("Kisumu E", "N. Imenti"), squash
8
+ several words into one token ("KCN" -> "Kitutu Chache North", "Homabay"),
9
+ list words in a different order ("Imenti N" -> "North Imenti"), or name
10
+ only some of the words ("Kisumu" -> "Kisumu East", scored lower).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import difflib
16
+ from itertools import combinations, permutations
17
+ from typing import Iterator, List, Optional, Sequence, Tuple
18
+
19
+ Tokens = Tuple[str, ...]
20
+
21
+ _REORDER_FACTOR = 0.95
22
+ _MULTIWORD_TOKEN_FACTOR = 0.95
23
+ _FUZZY_THRESHOLD = 0.8
24
+ _FUZZY_WEIGHT = 0.75
25
+
26
+
27
+ def _is_subsequence_abbr(abbr: str, word: str) -> bool:
28
+ if not abbr or not word or abbr[0] != word[0]:
29
+ return False
30
+ it = iter(word)
31
+ return all(ch in it for ch in abbr)
32
+
33
+
34
+ def token_score(abbr: str, word: str) -> float:
35
+ """Score how well a single token abbreviates a single word (0 = no)."""
36
+ if abbr == word:
37
+ return 1.0
38
+ if word.startswith(abbr):
39
+ return 0.85 + 0.1 * len(abbr) / len(word)
40
+ if _is_subsequence_abbr(abbr, word):
41
+ last_letter_bonus = 0.05 if abbr[-1] == word[-1] else 0.0
42
+ return 0.7 + 0.1 * len(abbr) / len(word) + last_letter_bonus
43
+ return 0.0
44
+
45
+
46
+ def _splits(token: str, words: Sequence[str]) -> Iterator[List[float]]:
47
+ """Ways to split one query token across all of ``words``, in order."""
48
+ if len(words) == 1:
49
+ s = token_score(token, words[0])
50
+ if s:
51
+ yield [s]
52
+ return
53
+ for i in range(1, len(token)):
54
+ s = token_score(token[:i], words[0])
55
+ if s:
56
+ for rest in _splits(token[i:], words[1:]):
57
+ yield [s] + rest
58
+
59
+
60
+ def _mean(xs: Sequence[float]) -> float:
61
+ return sum(xs) / len(xs)
62
+
63
+
64
+ def _cover(query: Sequence[str], words: Sequence[str]) -> Optional[List[float]]:
65
+ """Best per-word scores when ``query`` covers all ``words`` in order."""
66
+ if not query:
67
+ return [] if not words else None
68
+ best: Optional[List[float]] = None
69
+ max_take = len(words) - len(query) + 1
70
+ for take in range(1, max_take + 1):
71
+ for scores in _splits(query[0], words[:take]):
72
+ if take > 1:
73
+ scores = [s * _MULTIWORD_TOKEN_FACTOR for s in scores]
74
+ rest = _cover(query[1:], words[take:])
75
+ if rest is None:
76
+ continue
77
+ cand = scores + rest
78
+ if best is None or _mean(cand) > _mean(best):
79
+ best = cand
80
+ return best
81
+
82
+
83
+ def score(query: Tokens, name: Tokens) -> Tuple[float, str]:
84
+ """Score ``query`` against ``name``. Returns ``(score, method)``.
85
+
86
+ ``method`` is ``exact``, ``abbreviation``, ``partial``, ``fuzzy`` or ``""``
87
+ when there is no match.
88
+ """
89
+ if not query or not name:
90
+ return 0.0, ""
91
+ if query == name:
92
+ return 1.0, "exact"
93
+
94
+ best, method = 0.0, ""
95
+ n = len(name)
96
+ # Cheap pre-filter: the query must start like some word of the name.
97
+ first_letters = {w[0] for w in name}
98
+ if query[0][0] in first_letters:
99
+ for size in range(n, 0, -1):
100
+ for subset in combinations(range(n), size):
101
+ for order in permutations(subset):
102
+ words = [name[i] for i in order]
103
+ scores = _cover(query, words)
104
+ if scores is None:
105
+ continue
106
+ s = _mean(scores)
107
+ if list(order) != sorted(order):
108
+ s *= _REORDER_FACTOR
109
+ if size < n:
110
+ s *= 0.6 + 0.3 * size / n
111
+ if s > best:
112
+ best = s
113
+ method = "abbreviation" if size == n else "partial"
114
+
115
+ ratio = difflib.SequenceMatcher(None, " ".join(query), " ".join(name)).ratio()
116
+ if ratio >= _FUZZY_THRESHOLD and ratio * _FUZZY_WEIGHT > best:
117
+ best, method = ratio * _FUZZY_WEIGHT, "fuzzy"
118
+
119
+ return best, method
@@ -0,0 +1,76 @@
1
+ """Data types used throughout the library."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from enum import Enum
7
+ from typing import Optional, Tuple
8
+
9
+
10
+ class Kind(str, Enum):
11
+ """The type of administrative unit."""
12
+
13
+ COUNTY = "county"
14
+ CONSTITUENCY = "constituency"
15
+ SUBCOUNTY = "subcounty"
16
+ DISTRICT = "district"
17
+
18
+
19
+ # Lower number wins when two matches have the same score.
20
+ KIND_PRIORITY = {
21
+ Kind.COUNTY: 0,
22
+ Kind.CONSTITUENCY: 1,
23
+ Kind.SUBCOUNTY: 2,
24
+ Kind.DISTRICT: 3,
25
+ }
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class Place:
30
+ """An administrative unit of Kenya.
31
+
32
+ Attributes:
33
+ name: Official name, e.g. ``"Kisumu East"``.
34
+ kind: County, constituency, sub-county or (former) district.
35
+ code: Official code where one exists: the 3-digit county code for
36
+ counties, the 3-digit IEBC code for constituencies and
37
+ sub-counties. ``None`` for districts.
38
+ county: Name of the parent county (constituencies and sub-counties).
39
+ province: Former (pre-2013) province (counties and districts).
40
+ aliases: Alternative spellings and common abbreviations.
41
+ """
42
+
43
+ name: str
44
+ kind: Kind
45
+ code: Optional[str] = None
46
+ county: Optional[str] = None
47
+ province: Optional[str] = None
48
+ aliases: Tuple[str, ...] = ()
49
+
50
+ def __str__(self) -> str:
51
+ parent = self.county or self.province
52
+ suffix = f", {parent}" if parent else ""
53
+ code = f" [{self.code}]" if self.code else ""
54
+ return f"{self.name} ({self.kind.value}{suffix}){code}"
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class Match:
59
+ """A candidate place for an abbreviation.
60
+
61
+ Attributes:
62
+ place: The matched place.
63
+ score: Confidence between 0 and 1. 1.0 is an exact name match.
64
+ matched: The name or alias that the query was matched against.
65
+ method: How it matched: ``exact``, ``alias``, ``abbreviation``,
66
+ ``partial`` (query covers only some words of the name) or
67
+ ``fuzzy`` (spelling-error tolerant).
68
+ """
69
+
70
+ place: Place
71
+ score: float
72
+ matched: str
73
+ method: str
74
+
75
+ def __str__(self) -> str:
76
+ return f"{self.place} score={self.score:.2f} via {self.method} ({self.matched!r})"
@@ -0,0 +1,33 @@
1
+ """Text normalisation shared by names and queries."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import unicodedata
7
+ from typing import Tuple
8
+
9
+ # Words that describe the unit type rather than name it.
10
+ _UNIT_WORDS = re.compile(
11
+ r"\b(sub[\s\-_]*count(?:y|ies)|count(?:y|ies)|constituenc(?:y|ies)"
12
+ r"|district|dist|const)\b"
13
+ )
14
+ _APOSTROPHES = re.compile(r"['‘’`]")
15
+ _NON_ALNUM = re.compile(r"[^a-z0-9]+")
16
+
17
+
18
+ def tokenize(text: str) -> Tuple[str, ...]:
19
+ """Lower-case, strip accents, punctuation and unit words; split to words.
20
+
21
+ >>> tokenize("Murang'a County")
22
+ ('muranga',)
23
+ >>> tokenize("Chuka/Igambang'ombe")
24
+ ('chuka', 'igambangombe')
25
+ >>> tokenize("Mount Elgon Sub-County")
26
+ ('mt', 'elgon')
27
+ """
28
+ text = unicodedata.normalize("NFKD", text)
29
+ text = "".join(c for c in text if not unicodedata.combining(c)).lower()
30
+ text = _APOSTROPHES.sub("", text)
31
+ text = _UNIT_WORDS.sub(" ", text)
32
+ tokens = [t for t in _NON_ALNUM.split(text) if t]
33
+ return tuple("mt" if t == "mount" else t for t in tokens)
@@ -0,0 +1,235 @@
1
+ """Builds the place index and exposes lookup/identification functions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from functools import lru_cache
6
+ from typing import Dict, Iterable, List, Optional, Tuple, Union
7
+
8
+ from . import _data
9
+ from .matcher import score
10
+ from .models import KIND_PRIORITY, Kind, Match, Place
11
+ from .normalize import tokenize
12
+
13
+ KindLike = Union[Kind, str]
14
+
15
+ _ALIAS_EXACT_SCORE = 0.99
16
+ _ALIAS_FACTOR = 0.97
17
+ DEFAULT_MIN_SCORE = 0.6
18
+
19
+
20
+ def _unpack(entry) -> Tuple[str, Tuple[str, ...]]:
21
+ if isinstance(entry, tuple):
22
+ return entry[0], tuple(entry[1])
23
+ return entry, ()
24
+
25
+
26
+ @lru_cache(maxsize=None)
27
+ def _places() -> Tuple[Place, ...]:
28
+ places: List[Place] = []
29
+ county_names: Dict[str, str] = {}
30
+ for code, name, province, aliases in _data.COUNTIES:
31
+ county_names[code] = name
32
+ places.append(Place(name, Kind.COUNTY, code, None, province, aliases))
33
+
34
+ number = 0
35
+ for county_code, entries in _data.CONSTITUENCIES.items():
36
+ county = county_names[county_code]
37
+ for entry in entries:
38
+ number += 1
39
+ name, aliases = _unpack(entry)
40
+ code = f"{number:03d}"
41
+ for kind in (Kind.CONSTITUENCY, Kind.SUBCOUNTY):
42
+ places.append(Place(name, kind, code, county, None, aliases))
43
+
44
+ for province, entries in _data.DISTRICTS.items():
45
+ for entry in entries:
46
+ name, aliases = _unpack(entry)
47
+ places.append(Place(name, Kind.DISTRICT, None, None, province, aliases))
48
+ return tuple(places)
49
+
50
+
51
+ @lru_cache(maxsize=None)
52
+ def _index() -> Tuple[Tuple[Place, Tuple[Tuple[str, Tuple[str, ...], bool], ...]], ...]:
53
+ """(place, ((label, tokens, is_alias), ...)) for every place."""
54
+ out = []
55
+ for place in _places():
56
+ forms = [(place.name, tokenize(place.name), False)]
57
+ forms += [(a, tokenize(a), True) for a in place.aliases]
58
+ out.append((place, tuple(forms)))
59
+ return tuple(out)
60
+
61
+
62
+ def _coerce_kinds(kinds: Optional[Iterable[KindLike]]) -> Optional[set]:
63
+ if kinds is None:
64
+ return None
65
+ if isinstance(kinds, (str, Kind)):
66
+ kinds = [kinds]
67
+ return {Kind(k) for k in kinds}
68
+
69
+
70
+ def identify(
71
+ query: str,
72
+ kinds: Optional[Union[KindLike, Iterable[KindLike]]] = None,
73
+ county: Optional[str] = None,
74
+ limit: Optional[int] = 10,
75
+ min_score: float = DEFAULT_MIN_SCORE,
76
+ ) -> List[Match]:
77
+ """Find the places an abbreviation (or misspelling) may refer to.
78
+
79
+ Args:
80
+ query: e.g. ``"Msa"``, ``"Kisumu E"``, ``"N. Imenti"``, ``"KCN"``.
81
+ kinds: Restrict to one or more of ``"county"``, ``"constituency"``,
82
+ ``"subcounty"``, ``"district"`` (or :class:`Kind` values).
83
+ county: Restrict constituencies/sub-counties to this county, and
84
+ counties to this county (the name may itself be abbreviated).
85
+ limit: Maximum number of results (``None`` for all).
86
+ min_score: Drop matches scoring below this (0-1).
87
+
88
+ Returns:
89
+ Matches, best first.
90
+ """
91
+ q = tokenize(query)
92
+ if not q:
93
+ return []
94
+ wanted = _coerce_kinds(kinds)
95
+ county_filter = _resolve_county(county) if county else None
96
+
97
+ matches: List[Match] = []
98
+ for place, forms in _index():
99
+ if wanted is not None and place.kind not in wanted:
100
+ continue
101
+ if county_filter is not None:
102
+ in_county = place.county or (place.name if place.kind is Kind.COUNTY else None)
103
+ if in_county != county_filter:
104
+ continue
105
+ best: Optional[Match] = None
106
+ for label, tokens, is_alias in forms:
107
+ s, method = score(q, tokens)
108
+ if not s:
109
+ continue
110
+ if is_alias:
111
+ if method == "exact":
112
+ s, method = _ALIAS_EXACT_SCORE, "alias"
113
+ else:
114
+ s *= _ALIAS_FACTOR
115
+ if best is None or s > best.score:
116
+ best = Match(place, round(s, 4), label, method)
117
+ if best is not None and best.score >= min_score:
118
+ matches.append(best)
119
+
120
+ matches.sort(key=lambda m: (-m.score, KIND_PRIORITY[m.place.kind], m.place.name))
121
+ return matches if limit is None else matches[:limit]
122
+
123
+
124
+ def best_match(
125
+ query: str,
126
+ kinds: Optional[Union[KindLike, Iterable[KindLike]]] = None,
127
+ county: Optional[str] = None,
128
+ min_score: float = DEFAULT_MIN_SCORE,
129
+ ) -> Optional[Match]:
130
+ """The single most likely place for ``query``, or ``None``."""
131
+ found = identify(query, kinds=kinds, county=county, limit=1, min_score=min_score)
132
+ return found[0] if found else None
133
+
134
+
135
+ def expand(
136
+ query: str,
137
+ kinds: Optional[Union[KindLike, Iterable[KindLike]]] = None,
138
+ county: Optional[str] = None,
139
+ ) -> Optional[str]:
140
+ """Full official name for an abbreviation, e.g. ``"Msa"`` -> ``"Mombasa"``."""
141
+ m = best_match(query, kinds=kinds, county=county)
142
+ return m.place.name if m else None
143
+
144
+
145
+ def _resolve_county(county: str) -> str:
146
+ m = best_match(county, kinds=Kind.COUNTY)
147
+ if m is None:
148
+ raise ValueError(f"Unknown county: {county!r}")
149
+ return m.place.name
150
+
151
+
152
+ # --------------------------------------------------------------------------
153
+ # Listing
154
+
155
+
156
+ def places(kinds: Optional[Union[KindLike, Iterable[KindLike]]] = None) -> List[Place]:
157
+ """All places, optionally filtered by kind."""
158
+ wanted = _coerce_kinds(kinds)
159
+ return [p for p in _places() if wanted is None or p.kind in wanted]
160
+
161
+
162
+ def counties() -> List[Place]:
163
+ """The 47 counties, in county-code order."""
164
+ return places(Kind.COUNTY)
165
+
166
+
167
+ def constituencies(county: Optional[str] = None) -> List[Place]:
168
+ """The 290 constituencies in IEBC-code order, optionally for one county."""
169
+ return _children(Kind.CONSTITUENCY, county)
170
+
171
+
172
+ def subcounties(county: Optional[str] = None) -> List[Place]:
173
+ """County sub-counties (one per constituency, same codes)."""
174
+ return _children(Kind.SUBCOUNTY, county)
175
+
176
+
177
+ def districts(province: Optional[str] = None) -> List[Place]:
178
+ """Former (2009) districts, optionally for one former province."""
179
+ out = places(Kind.DISTRICT)
180
+ if province is not None:
181
+ key = tokenize(province.replace("Province", ""))
182
+ out = [p for p in out if tokenize(p.province or "") == key]
183
+ return out
184
+
185
+
186
+ def _children(kind: Kind, county: Optional[str]) -> List[Place]:
187
+ out = places(kind)
188
+ if county is not None:
189
+ name = _resolve_county(county)
190
+ out = [p for p in out if p.county == name]
191
+ return out
192
+
193
+
194
+ def get(code: str, kind: KindLike = Kind.CONSTITUENCY) -> Place:
195
+ """Look up a county or constituency/sub-county by its official code."""
196
+ kind = Kind(kind)
197
+ code = f"{int(code):03d}"
198
+ for p in places(kind):
199
+ if p.code == code:
200
+ return p
201
+ raise KeyError(f"No {kind.value} with code {code}")
202
+
203
+
204
+ # --------------------------------------------------------------------------
205
+ # Generating abbreviations
206
+
207
+ _DIRECTIONS = {"north": "N", "south": "S", "east": "E", "west": "W", "central": "C"}
208
+ _VOWELS = set("aeiou")
209
+
210
+
211
+ def _word_abbr(word: str) -> str:
212
+ if word in _DIRECTIONS:
213
+ return _DIRECTIONS[word]
214
+ if len(word) <= 3:
215
+ return word.upper()
216
+ consonants = [c for c in word[1:] if c not in _VOWELS]
217
+ return (word[0] + "".join(consonants)[:2]).upper()
218
+
219
+
220
+ def abbreviate(name: str) -> str:
221
+ """Short form for a place name.
222
+
223
+ Returns the curated abbreviation if the place has one (e.g. Mombasa ->
224
+ ``MSA``); otherwise one is generated: first letter plus the next two
225
+ consonants of each word, and N/S/E/W/C for compass words
226
+ (``"Kisumu East"`` -> ``"KSM E"``). Generated forms are a convention
227
+ of this library, not an official standard, and are not guaranteed
228
+ unique; :func:`identify` will resolve them back to the name.
229
+ """
230
+ match = best_match(name, min_score=0.95)
231
+ if match is not None:
232
+ for alias in match.place.aliases:
233
+ if alias.isupper() and alias.isalpha():
234
+ return alias
235
+ return " ".join(_word_abbr(w) for w in tokenize(name))
@@ -0,0 +1,97 @@
1
+ Metadata-Version: 2.4
2
+ Name: kenya-abbreviations
3
+ Version: 0.1.0
4
+ Summary: Identify abbreviations of Kenyan counties, constituencies, sub-counties and former districts.
5
+ License-Expression: MIT
6
+ Classifier: Programming Language :: Python :: 3
7
+ Classifier: Operating System :: OS Independent
8
+ Requires-Python: >=3.9
9
+ Description-Content-Type: text/markdown
10
+ Provides-Extra: dev
11
+ Requires-Dist: pytest>=7; extra == "dev"
12
+
13
+ # kenya-abbreviations
14
+
15
+ Identify abbreviations of Kenyan **counties**, **constituencies**, **sub-counties** and former **districts**. No dependencies; Python 3.9+.
16
+
17
+ ```python
18
+ from kenya_abbreviations import expand, identify, abbreviate
19
+
20
+ expand("Msa") # 'Mombasa'
21
+ expand("Kisumu E", kinds="constituency") # 'Kisumu East'
22
+ expand("N. Imenti", kinds="constituency") # 'North Imenti'
23
+ expand("Imenti N", kinds="district") # 'Imenti North'
24
+ expand("KCN") # 'Kitutu Chache North'
25
+ expand("Emb. East", kinds="district") # 'Embu East'
26
+ expand("Kibera") # 'Kibra'
27
+
28
+ for m in identify("Kisumu E"):
29
+ print(m)
30
+ # Kisumu East (constituency, Kisumu) [238] score=0.94 via abbreviation ('Kisumu East')
31
+ # Kisumu East (subcounty, Kisumu) [238] score=0.94 via abbreviation ('Kisumu East')
32
+ # Kisumu East (district, Nyanza) score=0.94 via abbreviation ('Kisumu East')
33
+
34
+ abbreviate("Kisumu East") # 'KSM E'
35
+ ```
36
+
37
+ ## Install
38
+
39
+ ```
40
+ pip install -e . # or: pip install -e ".[dev]" for pytest
41
+ ```
42
+
43
+ ## API
44
+
45
+ | Function | Purpose |
46
+ |---|---|
47
+ | `identify(query, kinds=None, county=None, limit=10, min_score=0.6)` | All candidate places for an abbreviation, best first, as `Match` objects (`place`, `score`, `matched`, `method`). |
48
+ | `best_match(query, ...)` | The top `Match`, or `None`. |
49
+ | `expand(query, ...)` | The top match's official name, or `None`. |
50
+ | `abbreviate(name)` | Short form of a name: the curated one if there is one (`MSA`, `NBI`, `KSM`, `NKR`, `UG`), otherwise generated. |
51
+ | `counties()`, `constituencies(county=None)`, `subcounties(county=None)`, `districts(province=None)` | List the reference data. |
52
+ | `get(code, kind="constituency")` | Look up by official code, e.g. `get(290)` gives Mathare and `get(47, "county")` gives Nairobi. |
53
+
54
+ `kinds` takes `"county"`, `"constituency"`, `"subcounty"`, `"district"`, a `Kind` value, or a list of these. `county=` narrows results to one county, and you can abbreviate the county name too (`county="Msa"`).
55
+
56
+ ### Command line
57
+
58
+ ```
59
+ kenya-abbr Msa
60
+ kenya-abbr "Kisumu E" --kind constituency
61
+ kenya-abbr Central --county Kisumu
62
+ kenya-abbr --abbreviate Kitutu Chache North
63
+ python -m kenya_abbreviations KCN
64
+ ```
65
+
66
+ ## How matching works
67
+
68
+ Kenya has no official abbreviation standard for these units, so the matcher recognises the ways people usually shorten names:
69
+
70
+ - **Shortened words:** each query word must start with the same letter as a name word, and its letters must appear in that word in order. Examples: `Msa` → Mombasa, `Twn` → Town, `E` → East.
71
+ - **One token per word:** `Kisumu E`, `Dagoretti N`, `Nkr Twn W`.
72
+ - **Several words squashed into one token:** `KCN` → Kitutu Chache North, `Homabay` → Homa Bay.
73
+ - **Words in a different order:** `Imenti N` → North Imenti. These score slightly lower.
74
+ - **Only some of the words:** `Chuka` → Chuka/Igambang'ombe. These score lower.
75
+ - **Misspellings:** `Kisumo` → Kisumu.
76
+ - **Ignored when matching:** case, apostrophes (`Murang'a` = `Muranga`), punctuation, `Mount`/`Mt.`, and unit words such as *County*, *Sub-County*, *Constituency* and *District*.
77
+
78
+ Exact names score 1.0 and curated aliases score 0.99. If two matches score the same, counties come first, then constituencies, then sub-counties, then districts.
79
+
80
+ Abbreviations are often ambiguous. For example, `Emb E` can mean Embu East (a district) or Embakasi East (a constituency). Use `identify()` to see all the candidates, or pass `kinds=` or `county=` to narrow them down.
81
+
82
+ ## Data and sources
83
+
84
+ | Kind | Count | Source |
85
+ |---|---|---|
86
+ | Counties | 47 | Constitution of Kenya 2010, First Schedule (codes 001–047), with former province |
87
+ | Constituencies | 290 | IEBC, 2012 boundaries (codes 001–290) |
88
+ | Sub-counties | 290 | County sub-counties. Under County Governments Act 2012, s.48(1)(a), these correspond to the constituencies and share their codes. |
89
+ | Districts | 208 | Government of Kenya district list, July 2009 (via Wikipedia, *Sub-counties of Kenya*), with former province. The source says this list is incomplete. |
90
+
91
+ Not included yet: the national-government administrative sub-counties (about 314 as of 2023), which differ from the constituencies in some counties. To add them or more aliases, edit `src/kenya_abbreviations/_data.py`.
92
+
93
+ ## Development
94
+
95
+ ```
96
+ python -m pytest --doctest-modules src tests
97
+ ```
@@ -0,0 +1,19 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/kenya_abbreviations/__init__.py
4
+ src/kenya_abbreviations/__main__.py
5
+ src/kenya_abbreviations/_data.py
6
+ src/kenya_abbreviations/cli.py
7
+ src/kenya_abbreviations/matcher.py
8
+ src/kenya_abbreviations/models.py
9
+ src/kenya_abbreviations/normalize.py
10
+ src/kenya_abbreviations/py.typed
11
+ src/kenya_abbreviations/registry.py
12
+ src/kenya_abbreviations.egg-info/PKG-INFO
13
+ src/kenya_abbreviations.egg-info/SOURCES.txt
14
+ src/kenya_abbreviations.egg-info/dependency_links.txt
15
+ src/kenya_abbreviations.egg-info/entry_points.txt
16
+ src/kenya_abbreviations.egg-info/requires.txt
17
+ src/kenya_abbreviations.egg-info/top_level.txt
18
+ tests/test_data.py
19
+ tests/test_identify.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ kenya-abbr = kenya_abbreviations.cli:main
@@ -0,0 +1 @@
1
+ kenya_abbreviations
@@ -0,0 +1,49 @@
1
+ from kenya_abbreviations import (
2
+ Kind,
3
+ constituencies,
4
+ counties,
5
+ districts,
6
+ get,
7
+ subcounties,
8
+ )
9
+
10
+
11
+ def test_counts():
12
+ assert len(counties()) == 47
13
+ assert len(constituencies()) == 290
14
+ assert len(subcounties()) == 290
15
+ assert len(districts()) == 208
16
+
17
+
18
+ def test_codes_are_sequential_and_unique():
19
+ assert [p.code for p in counties()] == [f"{i:03d}" for i in range(1, 48)]
20
+ assert [p.code for p in constituencies()] == [f"{i:03d}" for i in range(1, 291)]
21
+
22
+
23
+ def test_names_unique_within_kind():
24
+ for kind in Kind:
25
+ names = [p.name for p in (counties() if kind is Kind.COUNTY else
26
+ constituencies() if kind is Kind.CONSTITUENCY else
27
+ subcounties() if kind is Kind.SUBCOUNTY else
28
+ districts())]
29
+ assert len(names) == len(set(names)), kind
30
+
31
+
32
+ def test_known_codes():
33
+ assert get(1).name == "Changamwe"
34
+ assert get("290").name == "Mathare"
35
+ assert get(274).name == "Westlands"
36
+ assert get(47, "county").name == "Nairobi"
37
+ assert get(1, "county").name == "Mombasa"
38
+
39
+
40
+ def test_constituencies_by_county():
41
+ nairobi = constituencies("Nairobi")
42
+ assert len(nairobi) == 17
43
+ assert all(p.county == "Nairobi" for p in nairobi)
44
+ assert len(constituencies("Msa")) == 6 # county given as abbreviation
45
+
46
+
47
+ def test_districts_by_province():
48
+ assert len(districts("Nairobi")) == 4
49
+ assert len(districts("Western Province")) == 21
@@ -0,0 +1,78 @@
1
+ import pytest
2
+
3
+ from kenya_abbreviations import Kind, abbreviate, best_match, constituencies, expand, identify
4
+ from kenya_abbreviations.cli import main
5
+
6
+
7
+ @pytest.mark.parametrize(
8
+ "query, kind, expected",
9
+ [
10
+ ("Msa", None, "Mombasa"),
11
+ ("NBI", None, "Nairobi"),
12
+ ("Nrb", None, "Nairobi"),
13
+ ("KSM", None, "Kisumu"),
14
+ ("UG", None, "Uasin Gishu"),
15
+ ("Muranga", None, "Murang'a"),
16
+ ("Homabay", "county", "Homa Bay"),
17
+ ("Kisumu E", "constituency", "Kisumu East"),
18
+ ("N. Imenti", "constituency", "North Imenti"),
19
+ ("Imenti N", "constituency", "North Imenti"),
20
+ ("Imenti N", "district", "Imenti North"),
21
+ ("KCN", "constituency", "Kitutu Chache North"),
22
+ ("Nkr Twn W", "constituency", "Nakuru Town West"),
23
+ ("Dagoretti N", "subcounty", "Dagoretti North"),
24
+ ("Emb. East", "constituency", "Embakasi East"),
25
+ ("Emb. East", "district", "Embu East"),
26
+ ("Kibera", "constituency", "Kibra"),
27
+ ("Mount Elgon", "constituency", "Mt. Elgon"),
28
+ ("Lang'ata", "constituency", "Langata"),
29
+ ("Chuka", "constituency", "Chuka/Igambang'ombe"),
30
+ ("Kisumo", "county", "Kisumu"), # misspelling
31
+ ("Kisumu East Sub-County", "subcounty", "Kisumu East"),
32
+ ("Kieni E Dist", "district", "Kieni East"),
33
+ ],
34
+ )
35
+ def test_expand(query, kind, expected):
36
+ assert expand(query, kinds=kind) == expected
37
+
38
+
39
+ def test_match_carries_parent_and_code():
40
+ m = best_match("Kisumu E", kinds=Kind.CONSTITUENCY)
41
+ assert m.place.county == "Kisumu"
42
+ assert m.place.code == "238"
43
+ assert m.method == "abbreviation"
44
+
45
+
46
+ def test_county_filter():
47
+ m = best_match("Central", kinds="constituency", county="Kisumu")
48
+ assert m.place.name == "Kisumu Central"
49
+
50
+
51
+ def test_unknown_returns_nothing():
52
+ assert identify("xyzzy") == []
53
+ assert expand("") is None
54
+
55
+
56
+ def test_multiple_kinds_returned_by_default():
57
+ kinds = {m.place.kind for m in identify("Kisumu E")}
58
+ assert {Kind.CONSTITUENCY, Kind.SUBCOUNTY, Kind.DISTRICT} <= kinds
59
+
60
+
61
+ def test_abbreviate():
62
+ assert abbreviate("Mombasa") == "MSA"
63
+ assert abbreviate("Kisumu East") == "KSM E"
64
+
65
+
66
+ @pytest.mark.parametrize("place", constituencies(), ids=lambda p: p.name)
67
+ def test_generated_abbreviation_round_trips(place):
68
+ short = abbreviate(place.name)
69
+ names = [m.place.name for m in identify(short, kinds="constituency", limit=None)]
70
+ assert place.name in names
71
+
72
+
73
+ def test_cli(capsys):
74
+ assert main(["Msa", "-k", "county"]) == 0
75
+ assert "Mombasa" in capsys.readouterr().out
76
+ assert main(["xyzzy"]) == 1
77
+ assert main(["-a", "Kisumu", "East"]) == 0
78
+ assert capsys.readouterr().out.strip() == "KSM E"