0

設定

いくつかの .txt ファイルで、先頭に空白がない単語の最初の出現箇所を見つける必要があります。考えられるケースは次のとおりです。

-- * should succed
t1 = "hello\t999\nworld\t\900"
t2 = "world\t\900\nhello\t999\n"
t3 = "world world\t\900\nhello\t999\n"

-- * should fail
t4 = "world\t\900\nhello world\t999\n"
t5 = "hello world\t999\nworld\t\900"
t6 = "world hello\t999\nworld\t\900"

私のパーサーは hello に到達するまで任意の文字を消費するため、失敗するはずですが、現在 t6 は成功しています。これが私のパーサーです:

私の解決策

import Control.Applicative

import Data.Attoparsec.Text.Lazy
import Data.Attoparsec.Combinator
import Data.Text hiding (foldr)
import qualified Data.Text.Lazy as L (Text, pack)



-- * should succed
t1 = L.pack "hello\t999\nworld\t\900"
t2 = L.pack "world\t\900\nhello\t999\n"

-- * should fail
t3 = L.pack "world\t\900\nhello world\t999\n"
t4 = L.pack "hello world\t999\nworld\t\900"
t5 = L.pack "world hello\t999\nworld\t\900"

p = occur "hello"    

---- * discard all text until word `w` occurs, and find its only field `n`
occur :: String -> Parser (String, Int)
occur w = do
    pUntil w
    string . pack $ w
    string "\t"
    n <- natural 
    string "\n"
    return (w, read n)


-- * Parse a natural number
natural :: Parser String
natural = many1' digit

-- * skip over all words in Text stream until the word we want
pUntil :: String -> Parser String 
pUntil = manyTill anyChar . lookAhead . string . pack 
4

1 に答える 1

2

考慮すべきアプローチは次のとおりです。

{-# LANGUAGE OverloadedStrings #-}

import Control.Applicative

import Data.Attoparsec.Text.Lazy
import Data.Attoparsec.Combinator
import Data.Text hiding (foldr)
import qualified Data.Text.Lazy as L (Text, pack)
import Data.Monoid

natural = many1' digit

-- manyTill anyChar (try $ char c <* eof)

pair0 w = do
  string (w <> "\t")
  n <- natural
  string "\n"
  return n

pair1 w = do
  manyTill anyChar (try $ string ("\n" <> w <> "\t"))
  n <- natural
  string "\n"
  return n

pair w = pair0 w <|> pair1 w

t1 = "hello\t999\nworld\t\900"
t2 = "world\t\900\nhello\t999\n"
t3 = "world world\t\900\nhello\t999\n"

-- * should fail
t4 = "world\t\900\nhello world\t999\n"
t5 = "hello world\t999\nworld\t\900"
t6 = "world hello\t999\nworld\t\900"

test t = parseTest (pair "hello") (L.pack t)

main = do
  test t1; test t2; test t3
  test t4; test t5; test t6

アイデアはpair0、入力の先頭で指定されたキーとペアをpair1一致させ、改行の直後のペアを一致させることです。

キーは、パーサーが成功するmanyTill anyChar (try p)まで文字をスキップし続ける使用です。p

(ところで- @Cactusによって書かれた回答を読んでmanyTill、この使用法について学びました。)try

于 2016-08-15T21:56:07.787 に答える