extractSentence 提取包含关键词的句子
(text, keyword string)
| 133 | |
| 134 | // extractSentence 提取包含关键词的句子 |
| 135 | func (e *Extractor) extractSentence(text, keyword string) string { |
| 136 | idx := strings.Index(text, keyword) |
| 137 | if idx == -1 { |
| 138 | return "" |
| 139 | } |
| 140 | |
| 141 | // 转换为 rune 处理中文 |
| 142 | runes := []rune(text) |
| 143 | keywordRunes := []rune(keyword) |
| 144 | |
| 145 | // 找到关键词在 rune 中的位置 |
| 146 | runeIdx := 0 |
| 147 | byteCount := 0 |
| 148 | for i, r := range runes { |
| 149 | if byteCount >= idx { |
| 150 | runeIdx = i |
| 151 | break |
| 152 | } |
| 153 | byteCount += len(string(r)) |
| 154 | } |
| 155 | |
| 156 | // 句子结束符 |
| 157 | isSentenceEnd := func(r rune) bool { |
| 158 | return r == '。' || r == '!' || r == '?' || r == '\n' || |
| 159 | r == '.' || r == '!' || r == '?' |
| 160 | } |
| 161 | |
| 162 | // 向前找句子开始 |
| 163 | start := runeIdx |
| 164 | for start > 0 { |
| 165 | if isSentenceEnd(runes[start-1]) { |
| 166 | break |
| 167 | } |
| 168 | start-- |
| 169 | } |
| 170 | |
| 171 | // 向后找句子结束 |
| 172 | end := runeIdx + len(keywordRunes) |
| 173 | for end < len(runes) { |
| 174 | if isSentenceEnd(runes[end]) { |
| 175 | break |
| 176 | } |
| 177 | end++ |
| 178 | } |
| 179 | |
| 180 | // 使用 rune slice 提取句子 |
| 181 | sentence := strings.TrimSpace(string(runes[start:end])) |
| 182 | |
| 183 | // 限制长度(按 rune 计算) |
| 184 | sentenceRunes := []rune(sentence) |
| 185 | if len(sentenceRunes) > e.config.MaxExtractLength { |
| 186 | // 截取关键词前后的内容 |
| 187 | keywordIdx := strings.Index(sentence, keyword) |
| 188 | keywordRuneIdx := 0 |
| 189 | byteCount := 0 |
| 190 | for i, r := range sentenceRunes { |
| 191 | if byteCount >= keywordIdx { |
| 192 | keywordRuneIdx = i |