packages feed

Emping-0.3: 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:: GenParser Char a Char
comma = char ','

txtField :: GenParser Char a String
txtField = do { char '\"' ; 
                txt <- many (noneOf "\""); 
                char '\"'; return txt }
 
numField :: GenParser Char a String              
numField = many1 digit

getField :: GenParser Char a String
getField = do {many (char ' '); txtField <|> numField }

csvLine :: GenParser Char a [String]
csvLine = do { many comma; 
               fields <- (sepBy getField comma);
               many (char ' '); newline; 
               return fields }

csvTable :: GenParser Char a [[String]]
csvTable = many csvLine

getTable :: String -> IO [[String]]
getTable fname = do pares <- parseFromFile csvTable fname
                    let res = case pares of 
                               Right x -> x
                               Left err -> error (show err)
                    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
-}