phy*_*nfo 5 haskell character-encoding
虽然我经历了一堆 Haskell-encoding-problems-Questions,但我无法解决以下问题:
我想阅读许多不同的文本文件;文件的字符编码可能不一致,我使用的任何 readFile-Function 在读取某些文件时都会引发异常。
我试着把问题浓缩:下面的情况总结了它的核心。
import Prelude hiding (writeFile, readFile)
import qualified Text.Pandoc.UTF8 as UTF (readFile, writeFile, putStr, putStrLn)
import qualified Prelude as Prel (writeFile, readFile)
import Data.ByteString.Lazy (ByteString, writeFile, readFile)
Run Code Online (Sandbox Code Playgroud)
在 ghci 中,我得到以下结果:
*Main> Prel.readFile "Test/A.txt"
*** Exception: Test/A.txt: hGetContents: invalid argument (invalid byte sequence) "\226\8364
*Main> Prel.readFile "Test/C.txt"
"\8230\n"
*Main> UTF.readFile "Test/A.txt"
"\8221\n"
*Main> UTF.readFile "Test/C.txt"
*** Exception: Cannot decode byte '\x85':
Data.Text.Internal.Encoding.Fusion.streamUtf8: Invalid UTF-8 stream
Run Code Online (Sandbox Code Playgroud)
也许以下信息有帮助:
getLocaleEncoding收益率CP1252
*Main> readFile "Test/A.txt"
"\226\128\157\r\n"
*Main> readFile "Test/C.txt"
"\133\r\n"
我的问题是:如何捕捉/处理/避免这些字符编码错误?关键是:我事先不知道文本文件的编码,我需要一种适用于所有人的 readFile 方法。如果不可能并且在抛出异常时,我希望捕获异常并继续我的程序,以便能够尝试另一个 readFile 函数,或者只是跳过该文本文件并转到下一个。
由于其他答案提到的所有原因,这并不容易。但一切并没有失去。使用charsetDetect \xe2\x80\x93\xc2\xa0it\ 基于 Mozilla 算法,显然是 \xe2\x80\x93 来检测每个字节串的编码。然后将检测到的编码传递给text-icu或encoding进行解码。检测不适用于最奇怪和最深奥的文本编码,但它应该适用于其余的情况。
\n