使用语言环境处理文本文件,忽略非Ascii字符

时间:2014-05-28 09:02:52

标签: haskell

如何加载和打印此文件的内容? http://daiw.de/share/misc/2014-05-28_haskell/foo.txt

nice text: lalala.
mean german text: Größe!

我当前的示例代码

main :: IO ()
main = do
    content <- readFile "foo.txt"
    putStrLn content

产生以下输出:

nice text: lalala.
Main.hs: foo.txt: hGetContents: invalid argument (invalid byte sequence)

如果所有非Ascii字符都被虚拟字符替换或完全丢弃,那就完全没问题了。

2 个答案:

答案 0 :(得分:3)

GHC支持本地语言环境。只要你的本地环境合情合理,它就会“正常工作”:

$ runhaskell foo.hs
nice text: lalala.
mean german text: Größe!

设置例如

LANG=en_US.UTF-8

答案 1 :(得分:0)

刚刚写了这个,它现在对我有用:

import Data.Char
import Control.Applicative
import qualified Data.ByteString.Char8 as B

readFileAscii :: String -> IO String
readFileAscii path = B.unpack <$> B.map (clearChar '-') <$> B.readFile path
    where
        clearChar :: Char -> Char -> Char
        clearChar d c
            | c == '\r' || c == '\n' = c
            | c >= '\32' && c < '\128' = c
            | otherwise = d

main :: IO ()
main = do
    content <- readFileAscii "foo.txt"
    putStrLn $ content
    putStrLn $ map toUpper content

我希望这不是一个不干净的解决方案,以后会困扰我。如果不好,请告诉我。你可能已经注意到了,我是Haskell的初学者。

相关问题