永发信息网

如何让Erlang Shell打印出中文

答案:1  悬赏:10  手机版
解决时间 2021-11-23 21:16
  • 提问者网友:蓝琪梦莎
  • 2021-11-23 07:37
如何让Erlang Shell打印出中文
最佳答案
  • 五星知识达人网友:由着我着迷
  • 2021-11-23 08:41
让Erlang Shell打印中文,结合网上和实践做如下整理:
1.用io:format/2的~p打印中文,出来的是unicode编码的list;
用io:format/2的~ts打印中文,就可以打印出中文
[html] view plain copy
print?在CODE上查看代码片派生到我的代码片
1> io:format("test===~p~n",["测试"]).
test===[27979,35797]
ok
2> io:format("test====~ts~n",["测试"]).
test====测试
ok
2.代码中的中文都是以utf8编码过的,即把unicode编码过的list再次用utf8编码
[html] view plain copy
print?在CODE上查看代码片派生到我的代码片
3> xmerl_ucs:to_utf8([27979,35797]).
[230,181,139,232,175,149]
可以看到utf8编码后是一个0-255数组成的一个list,这是项目中经常输出的中文字符的日志。
3.为了输出中文,需要把utf8转换成unicode编码,即
[html] view plain copy
print?在CODE上查看代码片派生到我的代码片
4> unicode:characters_to_list(list_to_binary([230,181,139,232,175,149])).
[27979,35797]
5> io:format("test===~ts~n",[[27979,35797]]).
test===测试
ok
为了方便,写成一个方法,可以在项目中直接调用。
[html] view plain copy
print?在CODE上查看代码片派生到我的代码片
-module(print_log).
-export([log/2,
test/0]).
log(Format, Data)->
L = get_format_list(Format),
DataList=
lists:map(
fun({1, X}) ->
unicode:characters_to_list(iolist_to_binary(X));
({0, X}) ->
X
end, lists:zip(L, Data)),
io:format(Format,DataList).
get_format_list(Format) ->
get_format_list(Format, []).
get_format_list([], Acc) ->
Acc;
get_format_list([$~|L], Acc) ->
case L of
"ts" ++ Other ->
get_format_list(Other, Acc ++ [1]);
"n" ++ Other ->
get_format_list(Other, Acc);
_ ->
get_format_list(L, Acc ++ [0])
end;
get_format_list([_H|L],Acc) ->
get_format_list(L, Acc).
test()->
log("test===~ts",["测试"]).
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯