[英]Cassava Skip or Ignore Columns
所以我对简单用例的 Cassava 有一个很好的掌握,但我有一个 .csv 有 25 列,我只关心第 2 和第 5 列。 有没有办法对每一行进行部分解析,或者我是否需要在如下所示的 labmda 声明中进行 20 _ :: Text
参数声明?
Right v -> V.forM_ v $ \ (_ :: Text, thingA :: Text, _ :: Text, _ :: Text, _ :: Text, thingB :: Text,, _ :: Text, _ :: Text, _ :: Text ..... etc
编辑:还刚刚发现无论如何都没有 25 列 CSV 的实例,所以即使是我荒谬的 336 个字符签名也无法工作。
编辑':似乎一种解决方案可能是命名记录( 此处建议作为处理超宽文档的修复程序)
您可以FromRecord
编写自己的FromRecord
实例。 您只需要编写一个parseRecord
方法,它接受一个Record
(它是Vector Field
类型),在索引 1 和 4 处提取所需的列,并将它们加载到您的数据类型中。
类似以下内容将起作用:
{-# LANGUAGE OverloadedStrings #-}
import Data.Csv
import qualified Data.Vector as V
import Data.Text (Text)
data SomeFields = SomeFields Text Text deriving (Show)
instance FromRecord SomeFields where
parseRecord r = SomeFields <$> parseField (r V.! 1) <*> parseField (r V.! 4)
main = do
print $ (decode NoHeader "1,2,3,4,5,6,7\na,b,c,d,e,f,g\n"
:: Either String (V.Vector SomeFields))
最终以这种方式解决了它。
data ThingAtoThinBMapping = ThingAtoThinBMapping {
thingA :: Text
, thingB :: Text
} deriving (Eq, Show, Read)
instance FromNamedRecord ThingAtoThinBMapping where
parseNamedRecord r = ThingAtoThinBMapping
<$> r .: "thing_a"
<*> r .: "thing_b"
printABMap = do
csvData <- BL.readFile "reallywide.csv"
case decodeByNameWith decodeOpts csvData of
Left err -> putStrLn err
Right (h, v) -> do
putStrLn $ show h
V.forM_ v $ \ m ->
putStrLn $ show (thingA m, thingB m)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.