Is there a soundex function for python?
Asked Answered
L

3

8

Is there a soundex function for python and if not how would you go about making a soundex code?

Soundex
Code    Letters 
1   B, F, P, V  
2   C, G, J, K, Q, S, X, Z  
3   D, T    
4   L   
5   M, N    
6   R   
SKIP   A, E, H, I, O, U, W, Y, H, W, and Y

For example:

Jackson = J250

Washington = W252

Clement = C455

Ashcraft = A261

Wu = W000

Lenitalenitive answered 15/2, 2016 at 7:6 Comment(2)
The question is off topic for StackOverflow. (To help a you a bit, there is a soundex package which I found after Googling the title)Kolyma
@BhargavRao, why is this off topic?Puissant
D
6

Yes , you can use Fuzzy which is a python library implementing some phonetic algorithms.

sudo pip install fuzzy

>>> import fuzzy
>>> soundex = fuzzy.Soundex(4)
>>> soundex("Jackson")
'J250'
>>> soundex("Washington")
'W252'
>>> soundex("Clement")
'C453'
>>> soundex("Ashcraft")
'A261'
>>> soundex("Wu")
'W000'
Donella answered 1/1, 2017 at 12:11 Comment(0)
H
4

You can use jellyfish

sudo pip install jellyfish

print "Soundex\t\t=", jellyfish.soundex("Ala ma kaca")
>Soundex                = A452
#...
>Metaphone              = AL M KK
>NYSIIS                 = AL
>Match rating codex     = ALMKC
Higher answered 4/8, 2017 at 14:2 Comment(0)
T
4

Use the below soundex() function directly without installing any package!

Snippet taken from package Jellyfish > _jellyfish.py

Examples

print(soundex('kent')) # K530
print(soundex('Paul')) # P400
print(soundex('amnesty')) # A523

Code

import unicodedata
def soundex(s):

    if not s:
        return ""

    s = unicodedata.normalize("NFKD", s)
    s = s.upper()

    replacements = (
        ("BFPV", "1"),
        ("CGJKQSXZ", "2"),
        ("DT", "3"),
        ("L", "4"),
        ("MN", "5"),
        ("R", "6"),
    )
    result = [s[0]]
    count = 1

    # find would-be replacment for first character
    for lset, sub in replacements:
        if s[0] in lset:
            last = sub
            break
    else:
        last = None

    for letter in s[1:]:
        for lset, sub in replacements:
            if letter in lset:
                if sub != last:
                    result.append(sub)
                    count += 1
                last = sub
                break
        else:
            if letter != "H" and letter != "W":
                # leave last alone if middle letter is H or W
                last = None
        if count == 4:
            break

    result += "0" * (4 - count)
    return "".join(result)

Tildie answered 21/4, 2021 at 14:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.