読者です 読者をやめる 読者になる 読者になる

IT練習ノート

IT関連で調べたこと(実際は嵌ったこと)を書いています。

HaskellのCSV読み込み

Haskell

利用ライブラリ

Text.CSV

インポート

Prelude> import Text.CSV

1行読み込み

Prelude Text.CSV> parseCSVTest "aaa,bbb"
[["aaa","bbb"]]
Prelude Text.CSV> parseCSVTest "aaa,bbb,ccc"
[["aaa","bbb","ccc"]]

トリムはしない

Prelude Text.CSV> parseCSVTest "aaa,bbb,  ccc"
[["aaa","bbb","  ccc"]]

複数行読み込み

Prelude Text.CSV> parseCSVTest "aaa,bbb,  ccc\naaa,"
[["aaa","bbb","  ccc"],["aaa",""]]
Prelude Text.CSV> parseCSVTest "aaa,bbb,  ccc\naaa,,bbb"
[["aaa","bbb","  ccc"],["aaa","","bbb"]]

出力

Prelude Text.CSV> printCSV [["1","2","3"],["4","5"],["6"]]
"\"1\",\"2\",\"3\"\n\"4\",\"5\"\n\"6\""

読み込み件数取得

Prelude Text.CSV> parseCSVFromFile "./data/UNdata_Export_pork.csv" >>= \x ->  either (\x -> return 0) (return . length) x
1376

10行目出力

Prelude Text.CSV> parseCSVFromFile "./data/UNdata_Export_pork.csv" >>= \x -> return $ either (\x -> []) (\x -> x !! 10) x
["Albania","2009","Thousand metric tons","0.63",""]

全件出力

Prelude Text.CSV> either (\x -> putStrLn "error") (mapM_ (putStrLn . show)) =<< parseCSVFromFile "./data/UNdata_Export_pork.csv"
["Country or Area","Year","Unit","Value","Value Footnotes"]
["Albania","2013","Mil. USD","3.86207176515949",""]
["Albania","2013","Thousand metric tons","0.8",""]