Emping-0.2: src/CSVParse.hs
module CSVParse ( getTable ) where
import Text.ParserCombinators.Parsec
{- module: parse a table in Open Office Calc csv-format
empty lines are skipped
empty fields at the beginning of a line are skipped
a text field starts with " and ends with "
a numerical field consists of digits only
-}
comma = char ','
txtField = do { char '\"' ;
txt <- many (noneOf "\"");
char '\"'; return txt }
numField = many1 digit
getField = do {many (char ' '); txtField <|> numField }
csvLine = do { many comma;
fields <- (sepBy getField comma);
many (char ' '); newline;
return fields }
csvTable = many csvLine
getTable :: String -> IO [[String]]
getTable fname = do pares <- parseFromFile csvTable fname
let res = case pares of
Right res -> res
Left err -> error "CSVParse: Parse error in input file"
return (res)
-- test the table in csv format for parse errors
{-
test = do putStrLn "Enter CSV file:"
name <- getLine
res <- parseFromFile csvTable name
case res of Left err -> print err
Right xs -> print xs
-}