[英]processing text file with locale, ignore non-Ascii characters
如何加载和打印此文件的内容? 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字符替换为虚拟字符或将其完全删除,那完全可以。
GHC支持本地语言环境。 只要您的本地设置合理,它就会“起作用”:
$ runhaskell foo.hs
nice text: lalala.
mean german text: Größe!
设置例如
LANG=en_US.UTF-8
刚刚写了这个,它现在对我有用:
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的初学者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.