如何用有限的资源解析Haskell中的大型XML文件?

Kon*_*nos 5 profiling haskell xml-parsing

我想从Haskell中的大型XML文件(大约20G)中提取信息.由于它是一个大文件,我使用了Hexpath的 SAX解析函数.

这是我测试的一个简单代码:

import qualified Data.ByteString.Lazy as L
import Text.XML.Expat.SAX as Sax

parse :: FilePath -> IO ()
parse path = do
    inputText <- L.readFile path
    let saxEvents = Sax.parse defaultParseOptions inputText :: [SAXEvent Text Text]
    let txt = foldl' processEvent "" saxEvents
    putStrLn txt
Run Code Online (Sandbox Code Playgroud)

在Cabal中激活分析后,它表示parse.saxEvents占用了85%的已分配内存.我也用过foldr,结果是一样的.

如果processEvent变得足够复杂,程序会因stack space overflow错误而崩溃.

我究竟做错了什么?

Mic*_*ael 2

你不说是什么processEvent样子。原则上,使用惰性对惰性生成的输入进行严格的左折叠应该是没有问题的ByteString,所以我不确定您的情况出了什么问题。但是在处理巨大的文件时应该使用适合流式传输的类型!

事实上,hexpat确实有“流媒体”界面(就像xml-conduit)。它使用不太知名的List库和它定义的相当丑陋的List类。原则上,List 包中的ListT类型应该可以正常工作。由于缺乏组合器,我很快就放弃了,并List为包装版本编写了一个丑陋类的适当实例,Pipes.ListT然后用它导出普通Pipes.Producer函数,例如parseProduce. 为此所需的琐碎操作附在下面:PipesSax.hs

一旦我们有了,parseProducer我们就可以将 ByteString 或 Text Producer 转换为SaxEvents带有 Text 或 ByteString 组件的 Producer。下面是一些简单的操作。我用的是238M的“input.xml”;从查看来看,程序永远不需要超过 6 MB 的内存top

--Sax.hs大多数 IO 操作使用registerIds底部定义的管道,该管道是针对大量 xml 定制的,其中这是一个有效的 1000 片段http://sprunge.us/WaQK

{-#LANGUAGE OverloadedStrings #-}
import PipesSax ( parseProducer )
import Data.ByteString ( ByteString )
import Text.XML.Expat.SAX 
import Pipes  -- cabal install pipes pipes-bytestring 
import Pipes.ByteString (toHandle, fromHandle, stdin, stdout )
import qualified Pipes.Prelude as P
import qualified System.IO as IO
import qualified Data.ByteString.Char8 as Char8

sax :: MonadIO m => Producer ByteString m () 
                 -> Producer (SAXEvent ByteString ByteString) m ()
sax =  parseProducer defaultParseOptions

-- stream xml from stdin, yielding hexpat tagstream to stdout;
main0 :: IO ()
main0 =  runEffect $ sax stdin >-> P.print

-- stream the extracted 'IDs' from stdin to stdout
main1 :: IO ()
main1 = runEffect $ sax stdin >-> registryIds >-> stdout

-- write all IDs to a file
main2 =  
 IO.withFile "input.xml" IO.ReadMode $ \inp -> 
 IO.withFile "output.txt" IO.WriteMode $ \out -> 
   runEffect $ sax (fromHandle inp) >-> registryIds >-> toHandle out 

-- folds:
-- print number of IDs
main3 =  IO.withFile "input.xml" IO.ReadMode $ \inp -> 
           do n <- P.length $ sax (fromHandle inp) >-> registryIds
              print n

-- sum the meaningful part of the IDs - a dumb fold for illustration
main4 =  IO.withFile "input.xml" IO.ReadMode $ \inp ->
         do let pipeline =  sax (fromHandle inp) >-> registryIds >-> P.map readIntId
            n <- P.fold (+) 0 id pipeline
            print n
  where
   readIntId :: ByteString -> Integer
   readIntId = maybe 0 (fromIntegral.fst) . Char8.readInt . Char8.drop 2

-- my xml has tags with attributes that appear via hexpat thus:
-- StartElement "FacilitySite" [("registryId","110007915364")] 
-- and the like. This is just an arbitrary demo stream manipulation.
registryIds :: Monad m => Pipe (SAXEvent ByteString ByteString) ByteString m ()
registryIds = do 
  e <- await  -- we look for a 'SAXEvent'
  case e of -- if it matches, we yield, else we go to the next event
    StartElement "FacilitySite" [("registryId",a)] -> do yield a
                                                         yield "\n"
                                                         registryIds
    _ -> registryIds  
Run Code Online (Sandbox Code Playgroud)

--“库”:PipesSax.hs

这只是 newtypes Pipes.ListT 来获取适当的实例。我们不导出任何与标准 Pipes.Producer 概念相关的内容,List或者ListT只是使用标准 Pipes.Producer 概念。

{-#LANGUAGE TypeFamilies, GeneralizedNewtypeDeriving #-}
module PipesSax (parseProducerLocations, parseProducer) where 
import Data.ByteString (ByteString)
import Text.XML.Expat.SAX
import Data.List.Class
import Control.Monad
import Control.Applicative
import Pipes  
import qualified Pipes.Internal as I

parseProducer
  :: (Monad m, GenericXMLString tag, GenericXMLString text) 
  => ParseOptions tag text
  -> Producer ByteString m () 
  -> Producer (SAXEvent tag text) m ()
parseProducer opt  = enumerate . enumerate_ 
                     . parseG opt 
                     . Select_ . Select

parseProducerLocations
  :: (Monad m, GenericXMLString tag, GenericXMLString text) 
  => ParseOptions tag text
  -> Producer ByteString m () 
  -> Producer (SAXEvent tag text, XMLParseLocation) m ()
parseProducerLocations opt = 
  enumerate . enumerate_ . parseLocationsG opt . Select_ . Select  

newtype ListT_ m a = Select_ { enumerate_ :: ListT m a }
    deriving (Functor, Monad, MonadPlus, MonadIO
             , Applicative, Alternative, Monoid, MonadTrans)

instance Monad m => List (ListT_ m) where
 type ItemM (ListT_ m) = m
 joinL = Select_ . Select . I.M . liftM (enumerate . enumerate_) 
 runList   = liftM emend  . next  . enumerate . enumerate_
   where 
     emend (Right (a,q)) = Cons a (Select_ (Select q))
     emend _ = Nil
Run Code Online (Sandbox Code Playgroud)