Coverage for geoparser/db/functions/soundex.py: 100%
20 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-20 18:08 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-20 18:08 +0000
1"""
2Soundex phonetic encoding for fuzzy matching candidate retrieval.
3"""
5# Soundex letter-to-digit mapping. Vowels (and y), as well as h and w, are not
6# included and are treated as non-coding letters.
7_SOUNDEX_CODES = {
8 "B": "1",
9 "F": "1",
10 "P": "1",
11 "V": "1",
12 "C": "2",
13 "G": "2",
14 "J": "2",
15 "K": "2",
16 "Q": "2",
17 "S": "2",
18 "X": "2",
19 "Z": "2",
20 "D": "3",
21 "T": "3",
22 "L": "4",
23 "M": "5",
24 "N": "5",
25 "R": "6",
26}
29def soundex(text: str) -> str:
30 """
31 Compute the American Soundex code for a string.
33 The Soundex code is a four-character phonetic hash consisting of the first
34 letter followed by three digits. It is used to retrieve candidate names that
35 sound alike before final ranking.
37 Args:
38 text: String to encode. May be None or contain non-alphabetic characters.
40 Returns:
41 Four-character Soundex code, or an empty string if there are no letters.
42 """
43 if not text:
44 return ""
46 letters = [char for char in text.upper() if char.isalpha()]
47 if not letters:
48 return ""
50 first = letters[0]
51 result = first
52 previous_code = _SOUNDEX_CODES.get(first, "")
54 for char in letters[1:]:
55 # h and w are transparent: they do not reset adjacency tracking, so two
56 # letters with the same code separated by h or w are coded only once.
57 if char in ("H", "W"):
58 continue
60 code = _SOUNDEX_CODES.get(char, "")
61 if code and code != previous_code:
62 result += code
63 if len(result) >= 4:
64 break
66 # Vowels (code "") reset adjacency, so identical codes separated by a
67 # vowel are coded twice.
68 previous_code = code
70 return (result + "000")[:4]