2013-06-13 71 views
0

我有一个文件充满句子包装在格式良好的XML(xmllint和tidylib这样说)。 所以这个xml看起来像这样:xml解析终止莫名其妙

<a id="100" attr1="text" attr1="text" attr1="text"> 
<tagname id="1"> 
This is my sentence. 
</tagname> 
</a> 
<a id="101" attr1="text" attr1="text" attr1="text"> 
<tagname id="1"> 
This is my sentence. 
</tagname> 
</a> 

等等。

我用下面的代码(从ID 1在这种情况下,以85)提取与属性句子

a1 = open(r"file.xml",'r') 
a = a1.readlines() 
a1.close() 
soup = BeautifulSoup(str(a)) 
for i in range(1,85): 
    a = soup.find('a', {'id': i}) 
    achild = a.find('tagname') 
    tagnametext = achild.contents 
    print tagnametext 

一切打印很好,直到句子84,在该收到错误: achild = a.find('tagname') AttributeError:'NoneType'对象没有属性'find'

每一组......都是用for循环生成的,所以xml都是一样的。 我用不同数量的句子尝试过不同的文件。发生错误的ID也会发生变化。 这是美丽的限制吗? 它不能扫描一定数量的行?

+0

这是什么ID号84是什么样子? – TerryA

回答

0

它在最后一行失败。它可能是一个文件编码问题,该行包含一些有趣的EOF字符,或者该行不被解释为字符串。你能打印出最后一行,然后看看它是什么类型?

0

最有可能a = soup.find('a', {'id': i})84不会返回您所期望的。 find()返回None如果找不到标记,则说明AttributeError

此外,在您的代码中,您似乎是BeautifulSouping列表(以字符串表示)。

soup = BeautifulSoup(str(a)) 

您正在对列表进行串联,然后将清单弄糟,这很愚蠢。如果汤整个文件,然后遍历每个标签,如果它有一个id

from bs4 import BeautifulSoup 
with open('file.xml', 'r') as myfile: 
    soup = BeautifulSoup(myfile.read()) 
    for i in soup.find_all('a', id=True): 
     print i.tagname.contents 

打印:

[u'\nThis is my sentence.\n'] 
[u'\nThis is my sentence.\n'] 
+0

soup = BeautifulSoup(myfile.read())崩溃我的Python空闲图形用户界面。该文件包含大约140,000个句子 – Jean

+0

@waterling可能不是最好的选择。 – TerryA