// Package normalize turns names and queries into a canonical form so // that trigram comparison meets in the middle. Importers store the // canonical form; the query pipeline applies the same rules, so // "State St" and "state street" compare equal. package normalize import ( "strings" "unicode" "golang.org/x/text/runes" "golang.org/x/text/transform" "golang.org/x/text/unicode/norm" ) var deaccent = transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC) // Text lowercases, strips accents, replaces punctuation with spaces, // and collapses whitespace. It does not expand abbreviations. func Text(s string) string { if flat, _, err := transform.String(deaccent, s); err == nil { s = flat } var b strings.Builder b.Grow(len(s)) space := true for _, r := range strings.ToLower(s) { switch { case unicode.IsLetter(r) || unicode.IsDigit(r): b.WriteRune(r) space = false case !space: b.WriteByte(' ') space = true } } return strings.TrimSpace(b.String()) } // abbreviations maps street types and directionals to one canonical // long form. Both stored names and queries pass through this map, so // expanding in one direction is enough for the two sides to agree. var abbreviations = map[string]string{ "ave": "avenue", "av": "avenue", "blvd": "boulevard", "cir": "circle", "ct": "court", "crt": "court", "cres": "crescent", "dr": "drive", "expy": "expressway", "hwy": "highway", "ln": "lane", "mt": "mount", "pkwy": "parkway", "pl": "place", "plz": "plaza", "pt": "point", "rd": "road", "rte": "route", "sq": "square", "st": "street", "ter": "terrace", "tpke": "turnpike", "trl": "trail", "n": "north", "s": "south", "e": "east", "w": "west", "ne": "northeast", "nw": "northwest", "se": "southeast", "sw": "southwest", } // Expand replaces abbreviated tokens with their canonical long form. // The input must already be in Text form. func Expand(s string) string { if s == "" { return "" } tokens := strings.Fields(s) for i, t := range tokens { if long, ok := abbreviations[t]; ok { tokens[i] = long } } return strings.Join(tokens, " ") } // Name is the canonical form stored in the *_norm columns. func Name(s string) string { return Expand(Text(s)) }