在Haskell中使用UTF-8作为IO String读取文件

问题描述 投票:9回答:3

除非文件有qazxsw poli字符,否则我有以下代码可以正常工作:

utf-8

使用utf-8字符,我得到了这个:qazxsw poi

由于我正在使用的文件有module Main where import Ref main = do text <- getLine theInput <- readFile text writeFile ("a"++text) (unlist . proc . lines $ theInput) 字符,我想处理此异常,以便重用从hGetContents: invalid argument (invalid byte sequence)导入的函数(如果可能)。

有没有办法读取UTF-8文件作为Ref所以我可以重用我的UTF-8的功能?我应该对我的代码做什么修改?提前致谢。

我附上了IO String模块的函数声明:

Ref

来自前奏:

Ref
haskell utf-8
3个回答
3
投票

这可以通过GHC的基本(但从标准扩展)unlist :: [String] -> String proc :: [String] -> [String] 模块完成,但您必须使用更多功能:

lines :: String -> [String]

2
投票

谢谢你的答案,但我自己找到了解决方案。实际上我正在使用的文件有这个编纂:

System.IO

因此,使用我的haskell代码处理该文件它应该具有此编码:

module Main where

import Ref
import System.IO

main = do
    text <- getLine
    inputHandle <- openFile text ReadMode 
    hSetEncoding inputHandle utf8
    theInput <- hGetContents inputHandle
    outputHandle <- openFile ("a"++text) WriteMode
    hSetEncoding outputHandle utf8
    hPutStr outputHandle (unlist . proc . lines $ theInput)
    hClose outputHandle -- I guess this one is optional in this case.

您可以使用实用程序ISO-8859 text, with CR line terminators 检查文件编码,如下所示:

UTF-8 Unicode text, with CR line terminators

要更改文件编码,请按照此file的说明进行操作!


1
投票

使用$ file filename

缺乏unicode支持是标准Haskell IO库的一个众所周知的问题。

link
© www.soinside.com 2019 - 2024. All rights reserved.