haskell - 将文本转换为 Unicode 转义序列

标签 haskell unicode character-encoding

我有一个 Text 对象,其中包含一些拉丁字符,需要将其转换为 \u#### 格式的 unicode 转义序列,其中 # 是十六进制数字

如上所述here ,haskell 可以轻松地将字符串转换为转义序列,反之亦然。但是,它只会转到十进制表示形式。例如,

> let s = "Ñ"
> s
"\209"

有没有办法指定转义序列编码以强制其以正确的格式吐出?即

> let s = encodeUnicode16 "Ñ"
> s
"\u00d1"

最佳答案

这个怎么样:

import Text.Printf (printf)

encodeUnicode16 :: String -> String
encodeUnicode16 = concatMap escapeChar
  where
    escapeChar c
        | ' ' <= c && c <= 'z' = [c]
        | otherwise =
            printf "\\u%04x" (fromEnum c)

我是ghci,你可以这样使用它:

> putStrLn $ encodeUnicode16 "Ñ"
\u00d1

请注意,如果您不使用 putStrLn 它将被转义两次:

> encodeUnicode16 "Ñ"
"\\u00d1"

这是因为 ghci 会在命令前面隐式添加 print

编辑:我错过了您有一个 Text 而不是 String 的部分。这是 Text 的相同代码:

import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Text.Printf (printf)

encodeUnicode16 :: Text -> Text
encodeUnicode16 = T.concatMap escapeChar
  where
    escapeChar c
        | ' ' <= c && c <= 'z' = T.singleton c
        | otherwise =
            T.pack $ printf "\\u%04x" (fromEnum c)

同样,您需要使用 T.putStrLn 来避免双重转义所有内容。

关于haskell - 将文本转换为 Unicode 转义序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39233848/

相关文章:

haskell - 数据构造函数的固定性声明

java.sql.SQLException : Incorrect string value: '\xF0\x9F\x91\xBD\xF0\x9F...' 异常

MySQL 1300 无效的 big5 字符串 : '\xC3\x97 '

.net - 在 .NET 中查找子字符串匹配的结尾

PHP 数据库中的错误字符集

haskell - "Modern"HList?

haskell - 无法匹配 haskell 中的多态类型

Haskell 新手问题 : What's wrong with my append function?

swift - 在 Swift 中将 UnicodeScalar 数组转换为字符串

html - "tall"右 V 形的 HTML unicode 字符是什么?