【问题标题】:Unexpected end of input with ParsecParsec 输入意外结束
【发布时间】:2015-06-20 13:19:30
【问题描述】:

我尝试用关键字之间的一系列数据解析以下文本文件:

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

通过使用以下haskell程序

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之间

你知道我的解析器出了什么问题以及如何纠正它吗?

【问题讨论】:

  • 请包含产生解析错误的实际代码(以及字符串输入或文本文件)。

标签: parsing haskell parsec


【解决方案1】:

你的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"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-22
    • 2016-08-05
    • 2018-01-23
    • 2020-07-10
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多