识别推文消息中正确的主题标签索引

2024-04-30

我需要识别 Twitter 消息(各种语言、表情符号等)中的正确索引。

我找不到返回这些位置的解决方案,如下例所示。

import (
    "regexp"
    "testing"

    "github.com/stretchr/testify/require"
)

func TestA(t *testing.T) {
    text := "???????? [URGENT] Les forces de dissuasion #nucleaire de la #Russie"

    var re = regexp.MustCompile(`#([_A-Za-z0-9]+)`)

    pos := re.FindAllStringIndex(text, -1)

    // FindAllStringIndex returns
    // [0][43,53]
    // [1][60,67]

    // These are the expected positions.

    require.Equal(t, pos[0][0], 37) 
    require.Equal(t, pos[0][1], 47)

    require.Equal(t, pos[1][0], 54)
    require.Equal(t, pos[1][1], 61)
}

The FindAllStringIndex() https://pkg.go.dev/regexp#Regexp.FindAllStringIndex函数返回字节的位置,而不是符文。

你需要import "unicode/utf8"并使用utf8.RuneCountInString(text[:pos[0][0]])等等而不是pos[0][0]确保计算 Unicode 代码点而不仅仅是字节:

// You can edit this code!
// Click here and start typing.
package main

import (
    "regexp"
    "testing"
    "unicode/utf8"

    "github.com/stretchr/testify/require"
)

func TestA(t *testing.T) {
    text := "???????? [URGENT] Les forces de dissuasion #nucleaire de la #Russie"

    var re = regexp.MustCompile(`#\w+`)

    pos := re.FindAllStringIndex(text, -1)

    require.Equal(t, utf8.RuneCountInString(text[:pos[0][0]]), 37)
    require.Equal(t, utf8.RuneCountInString(text[:pos[0][1]]), 47)
    require.Equal(t, utf8.RuneCountInString(text[:pos[1][0]]), 54)
    require.Equal(t, utf8.RuneCountInString(text[:pos[1][1]]), 61)

}

See the Go demo https://go.dev/play/p/WhBk6uYVd0M.

Also, #\w+是一个较短的模式来匹配#然后是一个或多个字母、数字或下划线。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

识别推文消息中正确的主题标签索引 的相关文章

随机推荐