forked from avito-tech/normalize
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnormalizers.go
More file actions
97 lines (83 loc) · 2.18 KB
/
normalizers.go
File metadata and controls
97 lines (83 loc) · 2.18 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package normalize
import (
"regexp"
"strings"
"unicode"
)
type Option func(string) string
var specialCharsPattern = regexp.MustCompile(`(?i:[^äöüa-zа-яё0-9])`)
// WithRemoveSpecialChars any char except latin/cyrillic letters, German umlauts (`ä`, `ö`, `ü`) and digits are removed
func WithRemoveSpecialChars() Option {
return func(str string) string {
return specialCharsPattern.ReplaceAllString(str, "")
}
}
var rareCyrillicChars = withUpperPairs(map[rune]rune{
'ё': 'е',
'й': 'и',
})
// WithFixRareCyrillicChars rare cyrillic letters `ё` and `й` are replaced with common equivalents `е` and `и`
func WithFixRareCyrillicChars() Option {
return WithRuneMapping(rareCyrillicChars)
}
var cyrillicTolatinsLookAlike = withUpperPairs(map[rune]rune{
'а': 'a',
'е': 'e',
'т': 't',
'у': 'y',
'о': 'o',
'р': 'p',
'н': 'h',
'к': 'k',
'х': 'x',
'с': 'c',
'б': 'b',
'м': 'm',
'д': 'd',
'л': 'l',
'в': 'b',
'г': 'g',
'ф': 'f',
})
// WithCyrillicToLatinLookAlike Latin/cyrillic look-alike pairs are normalized to latin letters so `В (в)` becomes `B (b)`, etc.
func WithCyrillicToLatinLookAlike() Option {
return WithRuneMapping(cyrillicTolatinsLookAlike)
}
var umlautsToLatin = withUpperPairs(map[rune]rune{
'ä': 'a',
'ö': 'o',
'ü': 'u',
})
// WithUmlautToLatinLookAlike german umlauts `ä`, `ö`, `ü` get converted to latin `a`, `o`, `u`
func WithUmlautToLatinLookAlike() Option {
return WithRuneMapping(umlautsToLatin)
}
// WithRuneMapping configures arbitrary rune mapping, case sensitive
func WithRuneMapping(mapping map[rune]rune) Option {
return func(str string) string {
return strings.Map(func(letter rune) rune {
if newLetter, ok := mapping[letter]; ok {
return newLetter
}
return letter
}, str)
}
}
func withUpperPairs(m map[rune]rune) map[rune]rune {
for from, to := range m {
m[unicode.ToUpper(from)] = unicode.ToUpper(to)
}
return m
}
// WithLowerCase converts string to lowercase
func WithLowerCase() Option {
return func(str string) string {
return strings.ToLower(str)
}
}
// WithNoNormalization applies no changes to string
func WithNoNormalization() Option {
return func(str string) string {
return str
}
}