unicode - 未读取 golang unicode/norm 迭代器的最后一个 rune

标签 unicode go normalization unicode-normalization

我正在使用 golang.org/x/text/unicode/norm 包在 []byte 中迭代 rune 。我选择这种方法是因为我需要检查每个 rune 并维护有关 rune 序列的信息。最后一次调用 iter.Next() 没有读取最后一个 rune 。它在最后一个 rune 上读取了 0 个字节。

代码如下:

package main

import (
  "fmt"
  "unicode/utf8"

  "golang.org/x/text/unicode/norm"
)

func main() {
  var (
    n   int
    r   rune
    it  norm.Iter
    out []byte
  )
  in := []byte(`test`)
  fmt.Printf("%s\n", in)
  fmt.Println(in)
  it.Init(norm.NFD, in)
  for !it.Done() {
    ruf := it.Next()
    r, n = utf8.DecodeRune(ruf)
    fmt.Printf("bytes read: %d. val: %q\n", n, r)
    buf := make([]byte, utf8.RuneLen(r))
    utf8.EncodeRune(buf, r)
    out = norm.NFC.Append(out, buf...)
  }
  fmt.Printf("%s\n", out)
  fmt.Println(out)
}

这会产生以下输出:

test
[116 101 115 116]
bytes read: 1. val: 't'
bytes read: 1. val: 'e'
bytes read: 1. val: 's'
bytes read: 0. val: '�'
tes�
[116 101 115 239 191 189]

最佳答案

这可能是 golang.org/x/text/unicode/norm 及其 Init() 函数中的错误。

在我看到的包的测试和示例中都使用了InitString。因此,作为解决方法,如果您更改:

 it.Init(norm.NFD, in)

到:

 it.InitString(norm.NFD, `test`)

事情会按预期进行。

我建议打开一个错误报告,但要注意,因为它在“/x”目录中,所以该包被 go 开发人员认为是实验性的。

(顺便说一句,我使用了我的 go debugger 来帮助我追踪发生了什么,但我应该说它的使用是我希望看到的那种调试器。)

关于unicode - 未读取 golang unicode/norm 迭代器的最后一个 rune ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31235584/

相关文章:

php - php 和 golang 之间的 lz4 问题

SQL规范化

security - 修复 ColdFusion 中的 Unicode 转换问题/漏洞

go - 在 Echo 中从查询字符串获取整数值的惯用方法是什么?

C++ 在 Unicode 而不是 Ansi 中创建文件

arrays - 避免在输入中使用空格

python - 数组的按列归一化(缩放)

javascript - 如何使用变量更改图像高度?

c# - 将 CJK 字符粘贴到 RichTextBox 会添加不需要的第二种字体

c++ - 查找 std::wstring 的字符长度