Simple library for fuzzy text sanitizing, normalizing and comparison.
People type differently. This may be a problem if you need to associate user input with some internal entity or compare two inputs of different users. Say abc-01
and ABC 01
must be considered to be the same strings in your system. There are many heuristics we can apply to make this work:
- Remove special characters.
- Convert everything to lowercase.
- etc.
This library is essentially an easily configurable set of useful helpers implementing all these transformations.
go get -u github.com/avito-tech/normalize
package main
import (
"fmt"
"github.com/avito-tech/normalize"
)
func main() {
fuzzy := "VAG-1101"
clean := normalize.Normalize(fuzzy)
fmt.Print(clean) // vag1101
manyFuzzy := []string{"VAG-1101", "VAG-1102"}
manyClean := normalize.Many(manyFuzzy)
fmt.Print(manyClean) // {"vag1101", "vag1102"}
}
- Any char except latin/cyrillic letters, German umlauts (
ä
,ö
,ü
) and digits are removed. - Rare cyrillic letters
ё
andй
are replaced with common equivalentsе
andи
. - Latin/cyrillic look-alike pairs are normalized to latin letters, so
В (в)
becomesB (b)
. Please check all replacement pairs inWithCyrillicToLatinLookAlike
normalizer innormalizers.go
. - German umlauts
ä
,ö
,ü
get converted to latina
,o
,u
. - The whole string gets lower cased.
Compare two strings with all normalizations described above applied. Provide threshold parameters to tweak how similar strings must be to make the function return true
.
threshold
is relative value, so 0.5
roughly means "strings are 50% different after all normalizations applied".
Levenstein distance is used under the hood to compute distance between strings.
package main
import (
"fmt"
"github.com/avito-tech/normalize"
)
func main() {
fuzzy := "Hyundai-Kia"
otherFuzzy := "HYUNDAI"
similarityThreshold := 0.3
result := normalize.AreStringsSimilar(fuzzy, otherFuzzy, similarityThreshold)
// distance(hyundaikia, hyundai) = 3
// 3 / len(hyundaikia) = 0.3
fmt.Print(result) // true
}
- Apply default normalization (described above).
- Calculate Levenstein distance and return
true
ifdistance / strlen <= threshold
.
Both AreStringsSimilar
and Normalize
accept arbitrary number of normalizers as an optional parameter.
Normalizer is any function that accepts string and returns string.
For example, following option will leave string unchanged.
package main
import "github.com/avito-tech/normalize"
func WithNoNormalization() normalize.Option {
return func(str string) string {
return str
}
}
You can configure normalizing to use only those options you need. For example, you can use only lower casing and cyr2lat conversion during normalization. Note that the order of options matters.
package main
import (
"fmt"
"github.com/avito-tech/normalize"
)
func main() {
fuzzy := "АВ-123"
clean := normalize.Normalize(fuzzy, normalize.WithLowerCase(), normalize.WithCyrillicToLatinLookAlike())
fmt.Print(clean) // ab-123
}