golang文本模糊匹配与规范化处理插件库normalize的使用

Golang文本模糊匹配与规范化处理插件库normalize的使用

简介

normalize是一个用于模糊文本清洗、规范化和比较的简单库。它可以帮助解决用户输入差异导致的问题,例如将"abc-01"和"ABC 01"视为相同字符串。

安装

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"}
}

默认规则(按实际应用顺序):

  1. 删除除拉丁/西里尔字母、德语变音符号(ä, ö, ü)和数字以外的任何字符
  2. 将罕见的西里尔字母ё和й替换为常见等效字母е和и
  3. 将拉丁/西里尔相似对规范化为拉丁字母,例如В(в)变为B(b)
  4. 将德语变音符号ä, ö, ü转换为拉丁字母a, o, u
  5. 整个字符串转换为小写

比较模糊文本

比较两个字符串,应用上述所有规范化。提供阈值参数来调整字符串必须有多相似才能使函数返回true。threshold是相对值,0.5大致表示"应用所有规范化后字符串有50%的不同"。

底层使用Levenshtein距离计算字符串之间的距离。

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
}

默认规则:

  1. 应用默认规范化(如上所述)
  2. 计算Levenshtein距离,如果distance/strlen <= threshold则返回true

配置

AreStringsSimilarNormalize都接受任意数量的规范化器作为可选参数。规范化器是任何接受字符串并返回字符串的函数。

例如,以下选项将使字符串保持不变:

package main

import "github.com/avito-tech/normalize"

func WithNoNormalization() normalize.Option {
	return func(str string) string {
		return str
	}
}

您可以配置规范化以仅使用所需的选项。例如,在规范化过程中可以仅使用小写转换和cyr2lat转换。注意选项的顺序很重要。

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
}

更多关于golang文本模糊匹配与规范化处理插件库normalize的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang文本模糊匹配与规范化处理插件库normalize的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


Golang文本模糊匹配与规范化处理:normalize库使用指南

在Go语言中处理文本模糊匹配和规范化是一个常见需求,normalize是一个实用的库,可以帮助我们实现这些功能。下面我将详细介绍如何使用这个库。

安装normalize库

首先需要安装该库:

go get github.com/avito-tech/normalize

基本功能

1. 文本规范化

package main

import (
	"fmt"
	"github.com/avito-tech/normalize"
)

func main() {
	// 基本规范化
	normalized := normalize.Normalize("Héllò Wörld! 123")
	fmt.Println(normalized) // 输出: hello world 123

	// 保留数字
	normalized = normalize.Normalize("Version 2.0", normalize.WithKeepNumbers())
	fmt.Println(normalized) // 输出: version 2.0

	// 自定义替换
	normalized = normalize.Normalize("$100", normalize.WithReplacement("$", "usd"))
	fmt.Println(normalized) // 输出: usd100
}

2. 模糊匹配

package main

import (
	"fmt"
	"github.com/avito-tech/normalize"
)

func main() {
	// 计算相似度
	similarity := normalize.Similarity("hello", "hallo")
	fmt.Printf("相似度: %.2f\n", similarity) // 输出: 相似度: 0.80

	// 带权重的相似度计算
	similarity = normalize.WeightedSimilarity("hello world", "hallo world", 
		normalize.WithWeights(0.7, 0.3)) // 第一个词权重0.7,第二个0.3
	fmt.Printf("加权相似度: %.2f\n", similarity)
}

高级用法

1. 自定义规范化规则

package main

import (
	"fmt"
	"github.com/avito-tech/normalize"
)

func main() {
	// 创建自定义规范化器
	customNormalizer := normalize.NewNormalizer(
		normalize.WithLowercase(),       // 转为小写
		normalize.WithTrimSpace(),       // 去除首尾空格
		normalize.WithRemovePunctuation(), // 移除标点
		normalize.WithReplacement("&", "and"), // 自定义替换
	)

	result := customNormalizer.Normalize("John & Jane's Café")
	fmt.Println(result) // 输出: john and janes cafe
}

2. 模糊搜索实现

package main

import (
	"fmt"
	"github.com/avito-tech/normalize"
)

func fuzzySearch(query string, candidates []string, threshold float64) []string {
	var results []string
	normalizedQuery := normalize.Normalize(query)
	
	for _, candidate := range candidates {
		normalizedCandidate := normalize.Normalize(candidate)
		similarity := normalize.Similarity(normalizedQuery, normalizedCandidate)
		
		if similarity >= threshold {
			results = append(results, candidate)
		}
	}
	
	return results
}

func main() {
	products := []string{
		"iPhone 13 Pro",
		"Samsung Galaxy S21",
		"Google Pixel 6",
		"Xiaomi Mi 11",
	}

	results := fuzzySearch("iphone 13", products, 0.7)
	fmt.Println("搜索结果:", results) // 输出: [iPhone 13 Pro]
}

性能优化建议

  1. 预处理数据:对于大量数据,预先规范化可以提高后续匹配速度
  2. 缓存结果:对频繁查询的文本缓存规范化结果
  3. 并行处理:对大规模数据集使用goroutine并行处理
package main

import (
	"fmt"
	"github.com/avito-tech/normalize"
	"sync"
)

func batchNormalize(texts []string) []string {
	var wg sync.WaitGroup
	results := make([]string, len(texts))
	normalizer := normalize.NewNormalizer()
	
	for i, text := range texts {
		wg.Add(1)
		go func(idx int, t string) {
			defer wg.Done()
			results[idx] = normalizer.Normalize(t)
		}(i, text)
	}
	
	wg.Wait()
	return results
}

func main() {
	texts := []string{"Text 1", "Text 2", "Text 3"}
	normalized := batchNormalize(texts)
	fmt.Println(normalized)
}

总结

normalize库为Go开发者提供了强大的文本处理能力,特别适合需要模糊匹配和文本规范化的场景。通过合理使用其提供的功能,可以显著提高文本处理的准确性和效率。

记住根据实际需求调整参数,如相似度阈值、规范化规则等,以获得最佳效果。

回到顶部