|
| 1 | +- [text 模块](#text-模块) |
| 2 | + - [SliceSame](#slicesame) |
| 3 | + - [Aho-Corasick automaton](#aho-corasick-automaton) |
| 4 | + - [计算文本编辑距离](#计算文本编辑距离) |
| 5 | + - [计算文本相似度](#计算文本相似度) |
| 6 | + |
1 | 7 | # text 模块 |
| 8 | +golang 里面的 strings 库已经有了很多丰富的字符串处理功能,但是都是偏向于基础处理。 |
| 9 | + |
| 10 | +text模块提供了一些字符串处理相关的算法能力。 |
| 11 | + |
| 12 | +## SliceSame |
| 13 | +- SliceSame——判断两个字符串数字是否相同。 |
| 14 | + |
| 15 | +example: [TestTextSim](https://github.com/memory-overflow/go-common-library/blob/main/text/text_test.go#L29) |
| 16 | +```go |
| 17 | +import ( |
| 18 | + "testing" |
| 19 | + |
| 20 | + "github.com/memory-overflow/go-common-library/text" |
| 21 | +) |
| 22 | + |
| 23 | +func TestTextSim(t *testing.T) { |
| 24 | + sim := text.TextSim("编辑距离测试", "测试一下距离") |
| 25 | + t.Logf("sim: %f", sim) |
| 26 | +} |
| 27 | +``` |
| 28 | + |
| 29 | +## Aho-Corasick automaton |
| 30 | +ac 自动机是一种多模式串的匹配算法。 |
| 31 | + |
| 32 | +一个常见的例子就是给出 n 个单词,再给出一段包含 m 个字符的文章,让你找出有多少个单词在文章里出现过。 |
| 33 | + |
| 34 | +比较容易想到的做法是,调用 n 次 `strings.Contains(s, xxx)`。假设 n 个单词平局长度为 k, 这样处理的算法时间复杂度为 O(n * k * m)。而使用 ac 自动机可以加速上述过程,整体算法时间复杂度只需要 O(n*k + m)。 |
| 35 | + |
| 36 | +example: [TestActrie](https://github.com/memory-overflow/go-common-library/blob/main/text/text_test.go#L9) |
| 37 | +```go |
| 38 | +import ( |
| 39 | + "testing" |
| 40 | + |
| 41 | + "github.com/memory-overflow/go-common-library/text" |
| 42 | +) |
| 43 | + |
| 44 | +func TestActrie(t *testing.T) { |
| 45 | + // 在字符串 "哈哈哈哈23434dfgdd" 中找出所有 "哈哈哈", "234","dfg" 出现的位置。 |
| 46 | + // 使用模式串构建一个 ac 自动机 |
| 47 | + ac := text.BuildAcTrie([]string{"哈哈哈", "234", "dfg"}) |
| 48 | + // 匹配母串 |
| 49 | + list, index := ac.Search("哈哈哈哈23434dfgdd") |
| 50 | + for i, l := range list { |
| 51 | + t.Log(l, index[i]) |
| 52 | + } |
| 53 | +} |
| 54 | +``` |
| 55 | + |
| 56 | +## 计算文本编辑距离 |
| 57 | +编辑距离(Edit Distance):是一个度量两个字符序列之间差异的字符串度量标准,两个单词之间的编辑距离是将一个单词转换为另一个单词所需的单字符编辑(插入、删除或替换)的最小数量。一般来说,编辑距离越小,两个串的相似度越大。 |
| 58 | + |
| 59 | +example: [TestActrie](https://github.com/memory-overflow/go-common-library/blob/main/text/text_test.go#L24) |
| 60 | +```go |
| 61 | +import ( |
| 62 | + "testing" |
| 63 | + |
| 64 | + "github.com/memory-overflow/go-common-library/text" |
| 65 | +) |
| 66 | + |
| 67 | +func TestLevenshtein(t *testing.T) { |
| 68 | + dist := text.Levenshtein([]rune("编辑距离测试"), []rune("测试一下距离")) |
| 69 | + t.Logf("dist: %d", dist) |
| 70 | +} |
| 71 | +``` |
| 72 | + |
| 73 | +## 计算文本相似度 |
| 74 | +通过编辑距离,计算两个文本的相似度。 |
| 75 | + |
| 76 | +example: [TestTextSim](https://github.com/memory-overflow/go-common-library/blob/main/text/text_test.go#L17) |
| 77 | +```go |
| 78 | +import ( |
| 79 | + "testing" |
| 80 | + |
| 81 | + "github.com/memory-overflow/go-common-library/text" |
| 82 | +) |
2 | 83 |
|
| 84 | +func TestTextSim(t *testing.T) { |
| 85 | + sim := text.TextSim("编辑距离测试", "测试一下距离") |
| 86 | + t.Logf("sim: %f", sim) |
| 87 | +} |
| 88 | +``` |
0 commit comments