1

我有一个大 (~50Mb) 文件,其中包含格式不佳的 XML 描述文档和<item> </item>标签之间的属性,我想从所有英文文档中提取文本

Python 的标准 XML 解析实用程序(dom、sax、expat)因格式错误而窒息,而更宽容的库(sgmllib、BeautifulSoup)解析整个文件并花费太长时间。

<item>
  <title>some title</title>
  <author>john doe</author>
  <lang>en</lang>
  <document> .... </document>
</item>

有谁知道<document> </document> 只有lang=en不解析整个文档的情况下才提取文本的方法?

附加信息:为什么它“格式不正确”

一些文档具有<dc:link></dc:link>导致解析器出现问题的属性。Python 的 xml.minidom 抱怨:

ExpatError: unbound prefix: line 13, column 0
4

4 回答 4

1

如果你有傻瓜

gawk 'BEGIN{
 RS="</item>"
 startpat="<document>"
 endpat="</document>"
 lpat=length(startpat)
 epat=length(endpat)
}
/<lang>en<\/lang>/{
    match($0,"<document>")
    start=RSTART
    match($0,"</document>")
    end=RSTART
    print substr($0,start+lpat,end-(start+lpat)) 
}' file

输出

$ more file
Junk
Junk
<item>
  <title>some title</title>
  <author>john doe</author>
  <lang>en</lang>
  <document> text
         i want blah ............  </document>
</item>
junk
junk
<item>
  <title>some title</title>
  <author>jane doe</author>
  <lang>ch</lang>
  <document> junk text
           ..       ............ </document>
</item>
junk
blahblah..
<item>
  <title>some title</title>
  <author>GI joe</author>
  <lang>en</lang>
  <document>  text i want ..... in one line  </document>
</item>
aksfh
aslkfj
dflkas

$ ./shell.sh
 text
         i want blah ............
  text i want ..... in one line
于 2009-11-11T01:24:10.720 回答
0

我认为,如果您对 Java 没问题,那么 VTD-XML 就可以正常工作,而不会出现那些未定义前缀的任何问题......

于 2009-11-11T01:00:01.440 回答
0

您将需要一些面向事件的解析器,例如 SAX,或在 .NET 中System.Xml.XmlReader

于 2009-11-10T20:17:31.083 回答
0

根据文档“损坏”的方式(以及严重程度),可能可以在 perl/python 中编写一个简单的过滤器,将其修复到足以通过 XML 格式良好的测试并将其转换为 DOM 或 XSLT。

您能否添加一些输入错误的示例?

于 2009-11-10T20:18:11.060 回答