2015-06-20 99 views
2

輸入意外結束我嘗試解析與關鍵詞之間的一系列數據下面的文本文件:用秒差距

many text many text many text 

BEGIN 
T LISTE2 
1 154 
2 321 
3 519 
4 520 
5 529 
6 426 
END 

many text many text many text 

通過下面的哈斯克爾程序

import Text.Parsec 
import Text.Parsec.String 
import Text.Parsec.Char 
import Text.Parsec.Combinator 

endOfLine :: Parser String 
endOfLine =  try (string "\n") 
      <|> try (string "\r\n") 

line = many $ noneOf "\n" 

parseListing = do 
    spaces 
    many $ noneOf "\n" 
    spaces 
    cont <- between (string "BEGIN\n") (string "END\n") $ endBy line endOfLine 
    spaces 
    many $ noneOf "\n" 
    spaces 
    eof 
    return cont 

main :: IO() 
main = do 
    file <- readFile ("test_list.txt") 
    case parse parseListing "(stdin)" file of 
      Left err -> do putStrLn "!!! Error !!!" 
          print err 
      Right resu -> do putStrLn $ concat resu 

當我分析我的文字文件,我得到以下錯誤:

"(stdin)" (line 16, column 1): 
unexpected end of input 
expecting "\n", "\r\n" or "END\n" 

我是一個新手解析,我不明白爲什麼失敗? 我的序列還在BEGINEND之間

你知道我的解析器出現了什麼問題,以及如何糾正它?

+1

請包括產生分析錯誤(以及字符串輸入或文本文件)的實際代碼。 –

回答

4

您的between永遠不會停止,因爲endBy line endOfLine也消耗任何行,並且END\n也是如此,所以它會吃掉越來越多的行,直到它失敗。 然後你的解析器試圖消耗string "END\n"並且失敗,這就是爲什麼錯誤信息提到"END\n" 你必須重寫行解析器在END\n上失敗。例如:

parseListing :: Parsec String() [String] 
parseListing = do 
    spaces 
    many $ noneOf "\n" 
    spaces 
    cont <- between begin end $ endBy (notFollowedBy end >> line) endOfLine 
    spaces 
    many $ noneOf "\n" 
    spaces 
    eof 
    return cont 
    where 
     begin = string "BEGIN\n" 
     end = string "END\n"