Go:如何找出 rune 的 Unicode 属性?

标签 go unicode

我想找出 rune 的 Unicode 属性,尤其是其脚本属性的值。 Unicode 是这样说的(在 http://www.unicode.org/reports/tr24/ 第 1.5 节):

The script property assigns a single value to each character, either
explicitly associating it with a particular script, or assigning one
of several specail [sic] values.

Go 的 unicode 包为我提供了一种方式来询问“这个 rune 在脚本 x 中吗?”,但我无法问“这个 rune 在什么脚本中?”。我显然可以遍历所有脚本,但那会很浪费。有没有更聪明的方法来找出 rune 的脚本? (我总是可以实现一个自组织列表,但我正在寻找标准的 go 库中的东西,它已经做了我想要的,但我忽略了。)

谢谢大家!

最佳答案

最简单快捷的解决方案是编写函数。例如,

package main

import (
    "fmt"
    "unicode"
)

var runeScript map[rune]string

func init() {
    const nChar = 128172 // Version 9.0.0
    runeScript = make(map[rune]string, nChar*125/100)
    for s, rt := range unicode.Scripts {
        for _, r := range rt.R16 {
            for i := r.Lo; i <= r.Hi; i += r.Stride {
                runeScript[rune(i)] = s
            }
        }
        for _, r := range rt.R32 {
            for i := r.Lo; i <= r.Hi; i += r.Stride {
                runeScript[rune(i)] = s
            }
        }
    }
}

func script(r rune) string {
    return runeScript[r]
}

func main() {
    chars := []rune{' ', '0', 'a', 'α', 'А', 'ㄱ'}
    for _, c := range chars {
        s := script(c)
        fmt.Printf("%q %s\n", c, s)
    }
}

输出:

$ go run script.go
' ' Common
'0' Common
'a' Latin
'α' Greek
'А' Cyrillic
'ㄱ' Hangul
$ 

关于Go:如何找出 rune 的 Unicode 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43044164/

相关文章:

xml - Golang 不时解码 mysql 格式。时间

go - 尝试安装 gonum 时如何处理 "import cycle not allowed"?

javascript - Unicode 字符不起作用

python - 如何让 IDLE 接受 Unicode 字符的粘贴?

go - PGP文件解密\

powershell - 如何在 Go 中使用 VirtualQueryEx 读取检索进程内存信息?

google-app-engine - 来自 Intuit IPP 的请求 token 请求被拒绝

Python 'ascii' 打印语句编码问题

python - Eclipse+PyDev 中的 unicode 字符串容差

python - 通过 ctypes 将 Unicode 字符串传递给 printf