~linuxgoose/linguistics-robin

ref: 0fded38e2d336f86d65b0b974f7f23880891e767 linguistics-robin/linguistics_robin/phonetics/metaphone.py -rw-r--r-- 1.5 KiB
0fded38elinuxgoose Update .github/workflows/publish.yml a month ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import re
from unidecode import unidecode

from ..utils import check_str, check_empty
from .phonetic_algorithm import PhoneticAlgorithm


class Metaphone(PhoneticAlgorithm):
    """
    The metaphone algorithm.

    [Reference]: https://en.wikipedia.org/wiki/Metaphone
    [Author]: Lawrence Philips, 1990
    """
    def __init__(self):
        super().__init__()

        self.rules = [
            (r'[^a-z]', r''),
            (r'([bcdfhjklmnpqrstvwxyz])\1+', r'\1'),
            (r'^ae', r'E'),
            (r'^[gkp]n', r'N'),
            (r'^wr', r'R'),
            (r'^x', r'S'),
            (r'^wh', r'W'),
            (r'mb$', r'M'),
            (r'(?!^)sch', r'SK'),
            (r'th', r'0'),
            (r't?ch|sh', r'X'),
            (r'c(?=ia)', r'X'),
            (r'[st](?=i[ao])', r'X'),
            (r's?c(?=[iey])', r'S'),
            (r'[cq]', r'K'),
            (r'dg(?=[iey])', r'J'),
            (r'd', r'T'),
            (r'g(?=h[^aeiou])', r''),
            (r'gn(ed)?', r'N'),
            (r'([^g]|^)g(?=[iey])', r'\1J'),
            (r'g+', r'K'),
            (r'ph', r'F'),
            (r'([aeiou])h(?=\b|[^aeiou])', r'\1'),
            (r'[wy](?![aeiou])', r''),
            (r'z', r'S'),
            (r'v', r'F'),
            (r'(?!^)[aeiou]+', r'')
        ]

    def phonetics(self, word):
        check_str(word)
        check_empty(word)

        code = unidecode(word).lower()
        for item in self.rules:
            code = re.sub(item[0], item[1], code)
        return code.upper()