2014-04-22 47 views
-2

雅虎CSV如何解析成陣列,例如開放[I],高[I],低[I],靠近[I]如何解析與秒差距

testhaskell.hs:22:5: 
    Couldn't match type `[]' with `IO' 
    Expected type: IO a0 
     Actual type: [a0] 
    In the return type of a call of `map' 
    In a stmt of a 'do' block: map (\ line -> sentence line) allLines 
    In the expression: 
     do { handle <- openFile 
         "C:\\Users\\ivan\\Downloads\\0388.HK.csv" ReadMode; 

      contents <- hGetContents handle; 
      let allLines = lines contents; 
      map (\ line -> sentence line) allLines; 
      .... } 

testhaskell.hs:22:19: 
    Couldn't match expected type `String -> a0' 
       with actual type `Text.Parsec.Prim.ParsecT 
            String() Data.Functor.Identity.Identity [String]' 

import System.IO 
import qualified Data.ByteString.Char8 as BS 
import qualified Data.ByteString as Str 
import Text.ParserCombinators.Parsec 

word :: Parser String 
word = many1 letter 

sentence :: Parser [String] 
sentence = do{ words <- sepBy1 word separator 
       ; oneOf ".?!" <?> "end of sentence" 
       ; return words 
       } 

separator :: Parser() 
separator = skipMany1 (space <|> char ',' <?> "") 

main = do 
    handle <- openFile "C:\\Users\\ivan\\Downloads\\0005.HK.csv" ReadMode 
    contents <- hGetContents handle 
    let allLines = lines contents 
    map (\line -> sentence line) allLines 
    --putStr contents 
    hClose handle 

更新:

module Main where 

import qualified Data.ByteString.Char8   as B 
import   Data.Map      ((!)) 
import   Data.Text 
import qualified Data.Vector     as V 
import   System.Directory 
import   Test.Framework     (Test, defaultMain, testGroup) 
import   Test.Framework.Providers.API 
import   Test.HUnit      ((@=?)) 

import   Data.CSV.Conduit 


main :: IO() 
main = defaultMain tests 


tests :: [Test] 
tests = [testGroup "Basic Ops" baseTests] 


baseTests :: [Test] 
baseTests = 
    [ 
    testCase "simple parsing works" test_simpleParse 
    ] 


test_simpleParse :: IO() 
test_simpleParse = do 
    (d :: V.Vector (MapRow B.ByteString)) <- readCSVFile csvSettings testFile1 
    V.mapM_ assertRow d 
    where 
    assertRow r = v3 @=? (v1 + v2) 
     where v1 = readBS $ r ! "Open" 
      v2 = readBS $ r ! "High" 
      v3 = readBS $ r ! "Low" 
      v4 = readBS $ r ! "Close" 


csvSettings :: CSVSettings 
csvSettings = defCSVSettings { csvQuoteChar = Just '`'} 

testFile1 :: FilePath 
testFile1 = "C:\\Users\\ivan\\Downloads\\0005.HK.csv" 


readBS :: B.ByteString -> Int 
readBS = read . B.unpack 

testhaskell.hs:52:5:不範圍:`測試用例」

testhaskell.hs:58:9: 非法類型簽名:'V.Vector(MapRow B.ByteString)」 也許你打算使用-XScopedTypeVariables 在模式類型的簽名

回答

5

我強烈推薦你不是這樣做。 Hackage上有許多高質量的CSV庫,並且自己推出是一個問題。在FP完成時,我們使用csv-conduit,但cassava也是一個偉大的庫。我建議你嘗試一下。

+0

任何示例顯示如何使用csv-conduit,我發現在github中的例子很難理解,目的只是返回打開數組,高數組,......關閉數組 – Moyes

+0

'readCSVFile'有什麼問題?它應該給你一個行的Vector,其中每一行都是Vector ByteString或Vector Text。如果你指的是你在上面添加的例子,編譯器會給你一些非常明確的指導如何解決它。 –