除非文件具有utf-8characteres,否则我有以下代码可以正常工作:
module Main where
import Ref
main = do
text <- getLine
theInput <- readFile text
writeFile ("a"++text) (unlist . proc . lines $ theInput)
Run Code Online (Sandbox Code Playgroud)
有了utf-8 characteres,我得到了这个:
hGetContents: invalid argument (invalid byte sequence)
由于我正在使用的文件有UTF-8字符,我想处理此异常,以便重用从中导入的函数(Ref如果可能).
有没有办法读取UTF-8文件,IO String因此我可以重用我Ref的函数?我应该对我的代码做什么修改?提前致谢.
我附加了我的Ref模块中的函数声明:
unlist :: [String] -> String
proc :: [String] -> [String]
Run Code Online (Sandbox Code Playgroud)
来自前奏:
lines :: String -> [String]
Run Code Online (Sandbox Code Playgroud)
这可以仅使用 GHC 的基本(但从标准扩展)System.IO模块来完成,尽管您将不得不使用更多功能:
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.
Run Code Online (Sandbox Code Playgroud)
感谢您的回答,但我自己找到了解决方案。实际上我正在使用的文件有这样的编码:
ISO-8859 text, with CR line terminators
Run Code Online (Sandbox Code Playgroud)
因此,要使用我的 haskell 代码处理该文件,它应该具有以下编码:
UTF-8 Unicode text, with CR line terminators
Run Code Online (Sandbox Code Playgroud)
您可以使用该实用程序检查文件编码,file如下所示:
$ file filename
Run Code Online (Sandbox Code Playgroud)
要更改文件编码,请按照此链接中的说明进行操作!
| 归档时间: |
|
| 查看次数: |
1748 次 |
| 最近记录: |