提问人:klsn 提问时间:1/15/2023 更新时间:1/15/2023 访问量:131
Erlang 格式的 UTF8 变为 \x(反斜杠 X)ASCII 编码
utf8 in erlang format becomes \x (backslash x) ascii encoded
问:
我想在我的 Linux 终端上打印一个 utf8 列表。
-module('main').
-export([main/1]).
main(_) ->
Text = "あいうえお",
io:format("~ts~n", [Text]),
halt().
当我在 Ubuntu22.04 上编译和运行时,
$ erlc main.erl
$ erl -noshell -run main main run
\x{3042}\x{3044}\x{3046}\x{3048}\x{304A}
它显示为 \x{3042}而不是 あ。
在 utf8 中,“あいうえお”应该有 15 个字节。 如何将 \x{3042} 拆分为 3 个字节并打印 あ?
顺便说一句,“あ”是一个日语字符。
list_to_bin不适用于 Unicode。
我找到了 unicode:characters_to_list 将 bin 转换为 unicode 的列表。 找不到相反的情况。
答:
3赞
estelio
1/15/2023
#1
如果要使用 Erlang 的 Unicode 输出,请删除 .添加 +pc unicode 也是很好的做法。-noshell
$ erl +pc unicode -run main main run
Erlang/OTP 24 [erts-12.2.1] [source] [64-bit] ...
あいうえお
在 Erlang 中,您可以将二进制文件指定为 utf8。例如,查看日文字符“あ”的三个字节二进制表示形式。
1> <<"あ"/utf8>>.
<<227,129,130>>
在示例中,采用字符串的第一个字形。
1> Text = "あいうえお".
[12354,12356,12358,12360,12362]
2> unicode:characters_to_binary(Text, unicode, utf8).
<<227,129,130,227,129,132,227,129,134,227,129,136,227,129,138>>
3> binary:part(unicode:characters_to_binary(Text, unicode, utf8),0,3).
<<227,129,130>>
4> io:format("~ts~n",[binary:part(unicode:characters_to_binary(Text, unicode, utf8),0,3)]).
あ
要将 unicode 保存到文件,请使用 erlang 的文件编码选项。
5> {ok,G} = file:open("/tmp/unicode.txt",[write,{encoding,utf8}]).
{ok,<0.148.0>}
6> io:put_chars(G,Text).
ok
7> file:close(G).
然后在壳中
$ file /tmp/unicode.txt
/tmp/unicode.txt: Unicode text, UTF-8 text, with no line terminators
$ cat /tmp/unicode.txt
あいうえお
评论