【问题标题】:How to stop Haskell Parsec parser at EOF如何在 EOF 停止 Haskell Parsec 解析器
【发布时间】:2016-12-23 07:21:07
【问题描述】:

所以,我正在编写一个小型解析器,它将提取具有特定类的所有 <td> 标记内容,例如 <td class="liste">some content</td> --> Right "some content"

我将解析大型 html 文件,但我并不真正关心所有噪音,所以我的想法是消耗所有字符直到达到 <td class="liste">,而不是消耗所有字符(内容)直到 @987654326 @ 并返回内容字符串。

如果文件中的最后一个元素是我的 td.liste 标记,这很好用,但如果我在它后面有一些文本或 eof,那么我的解析器会消耗它并在你执行 parseMyTest test3 时抛出 unexpected end of input

-- 编辑
请参阅test3 的末尾以了解什么是边缘情况。

到目前为止,这是我的代码:

import Text.Parsec
import Text.Parsec.String

import Data.ByteString.Lazy (ByteString)
import Data.ByteString.Char8 (pack)

colOP :: Parser String
colOP = string "<td class=\"liste\">"

colCL :: Parser String
colCL = string "</td>"

col :: Parser String
col = do
  manyTill anyChar (try colOP)
  content <- manyTill anyChar $ try colCL
  return content

cols :: Parser [String]
cols = many col

test1 :: String
test1 = "<td class=\"liste\">Hello world!</td>"

test2 :: String
test2 = read $ show $ pack test1

test3 :: String
test3 = "\n\r<html>asdfasd\n\r<td class=\"liste\">Hello world 1!</td>\n<td class=\"liste\">Hello world 2!</td>\n\rasldjfasldjf<td class=\"liste\">Hello world 3!</td><td class=\"liste\">Hello world 4!</td>adsafasd"

parseMyTest :: String -> Either ParseError [String]
parseMyTest test = parse cols "test" test

btos :: ByteString -> String
btos = read . show

【问题讨论】:

  • btw - 对于解析 HTML,我发现 tagsoup 效果很好。
  • 我知道,但我现在正在探索秒差距:D

标签: html parsing haskell parsec


【解决方案1】:

我创建了一个组合器 skipTill p end,它应用 p 直到 end 匹配,然后返回 end 返回的内容。

相比之下,manyTill p end 应用 p 直到 end 匹配,然后 返回 p 解析器匹配的内容。

import Text.Parsec
import Text.Parsec.String

skipTill :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m end -> ParsecT s u m end
skipTill p end = scan
    where
      scan  = end  <|> do { p; scan }

td :: Parser String
td = do
  string "("
  manyTill anyChar (try (string ")"))

tds = do r <- many (try (skipTill anyChar (try td)))
         many anyChar -- discard stuff at end
         return r

test1 = parse tds "" "111(abc)222(def)333" -- Right ["abc", "def"]

test2 = parse tds "" "111"                 -- Right []

test3 = parse tds "" "111(abc"             -- Right []

test4 = parse tds "" "111(abc)222(de"      -- Right ["abc"]

更新

这似乎也有效:

tds' = scan
  where scan = (eof >> return [])
               <|> do { r <- try td; rs <- scan; return (r:rs) }
               <|> do { anyChar; scan }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    • 2016-06-19
    • 2011-01-27
    相关资源
    最近更新 更多