在Go中将unicode代码点转换为文字字符 [英] Convert unicode code point to literal character in Go

查看:223
本文介绍了在Go中将unicode代码点转换为文字字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的文本文件。

  \\\S 
\\\u
\\

有没有一种方法可以将其转换为此?

  S 
u
n

目前,我正在使用 ioutil.ReadFile(data.txt),但是当我打印数据时,我得到了unicode代码点的字符串文字。我意识到这是 ReadFile 的正确行为,它只是不需要我想。



我的目标是用代码点替换它们的文字字符。 可以使用 strconv.Unquote() strconv.UnquoteChar() 可以进行转换。



你应该知道的一件事是 strconv.Unquote()只能引用引号中的字符串(例如开始和结束用引用char 或者引用char `),所以我们必须手动追加。



看下面的例子:

  lines:= [] string {
`\\\S`,
`\\\u`,
`\\
`,
}
fmt.Println(行)

对于我,v:= r ange lines {
var err error
lines [i],err = strconv.Unquote(``+ v +``)
if err!= nil {
fmt .Println(err)
}
}
fmt.Println(行)

fmt.Println(strconv.Unquote(`Go\\\p\x68 \x65\x72`))

输出(尝试在 Go Playground ):

  [\\\S \\\u \\
]
[S un]
Gopher< nil>


Let's say I have a text file like this.

\u0053
\u0075
\u006E

Is there a way I can convert that to this?

S
u
n

Currently, I'm using ioutil.ReadFile("data.txt"), but when I print the data, I get the unicode code points instead of the string literals. I realize this is the correct behavior for ReadFile, it's just not want I want.

I'm aiming for a substitution of the code points with their literal characters.

解决方案

You can use the strconv.Unquote() and strconv.UnquoteChar() functions to do the conversion.

One thing you should be aware of is that strconv.Unquote() can only unquote strings that are in quotes (e.g. start and end with a quote char " or a back quote char `), so we have to manually append that.

See this example:

lines := []string{
    `\u0053`,
    `\u0075`,
    `\u006E`,
}
fmt.Println(lines)

for i, v := range lines {
    var err error
    lines[i], err = strconv.Unquote(`"` + v + `"`)
    if err != nil {
        fmt.Println(err)
    }
}
fmt.Println(lines)

fmt.Println(strconv.Unquote(`"Go\u0070\x68\x65\x72"`))

Output (try it on the Go Playground):

[\u0053 \u0075 \u006E]
[S u n]
Gopher <nil>

这篇关于在Go中将unicode代码点转换为文字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆