如何将Unicode转义序列转换为Haskell中的Unicode字符串 [英] How to convert Unicode Escape Sequence to Unicode String in Haskell
问题描述
我有一个像\3619\3657\3634\3609\3648\3592\3657\3648\3621\3657\3591的字符串
我想解码它。我试图搜索unicode库,但没有成功。 前奏> putStrLn\3619\ 3657\\3634\\3609\\3648\\3592\\3657\\3648\\3621\\3657\\3591
请注意,您实际上没有字符串\3619\3657\3634\3609\3648\3592\3657 \ 3648\3621\3657\3591
–相反,您有UTF-32字符串ร้านเจ้เล้ง
,其中\3619\3657 ...$ c $恰巧是一个符合ASCII的文字。默认情况下,GHCi使用
Show
实例来显示结果,这并不像显示可以用作Haskell代码的文字那样显示结果。在unicode方面它是保守的。这就是为什么
Prelude>
\3619\3657\3634\ 3609 \ 3648 \ 3592 \ 3657 \ 3648 \ 3621 \ 3657 \ 3591
另一方面, putStrLn
, putChar
, hPutStr
等功能只需以UTF-8格式转储字符串本身,而不是以ASCII安全表示形式。
如果您实际上是从文件或某物中读取转义字符串,您可以只需阅读即可:
Prelude> s < - getLine
\\ \\ 3619 \\ 3657 \\ 3634 \\ 3609 \\ 3648 \\ 3592 \\ 3657 \\ 3648 \\ 3621 \\ 3657 \\ 3591
Prelude> s
\ \\3619\\3657\\3634\\3609\\3648\\3592\\3657\\3648\\3621\\ \3657\\\3591\
Prelude> putStrLn $ read s
$ >
I have a string like "\3619\3657\3634\3609\3648\3592\3657\3648\3621\3657\3591"
which I want to decode it. I tried search the unicode library without success.
Prelude> putStrLn "\3619\3657\3634\3609\3648\3592\3657\3648\3621\3657\3591"
ร้านเจ้เล้ง
Note that you don't actually have the string "\3619\3657\3634\3609\3648\3592\3657\3648\3621\3657\3591"
– rather, you have the UTF-32 string ร้านเจ้เล้ง
, for which "\3619\3657..."
happens to be a ASCII-compliant literal. By default, GHCi uses the Show
instance to display results, which doesn't so much show things as spit out literals that can be used as Haskell code for the thing. It's conservative in terms of unicode. That's why
Prelude> "ร้านเจ้เล้ง"
"\3619\3657\3634\3609\3648\3592\3657\3648\3621\3657\3591"
On the other hand, the putStrLn
, putChar
, hPutStr
etc. functions will just dump the string itself in UTF-8 rather than an ASCII-safe representation thereof.
If you're actually reading the escaped string from a file or something, you can simply read it:
Prelude> s <- getLine
"\3619\3657\3634\3609\3648\3592\3657\3648\3621\3657\3591"
Prelude> s
"\"\\3619\\3657\\3634\\3609\\3648\\3592\\3657\\3648\\3621\\3657\\3591\""
-- Note double escaping, because I'm showing a string that contains a string literal.
Prelude> putStrLn $ read s
ร้านเจ้เล้ง
这篇关于如何将Unicode转义序列转换为Haskell中的Unicode字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!