1

我有一个 TEI 编码的 xml 文件,其实体如下:

<sp>
    <speaker rend="italic">Sampson.</speaker>
    <ab>
         <lb n="5"/>
         <hi rend="italic">Gregory:</hi>
         <seg type="homograph">A</seg> my word wee'l not carry coales.<lb n="6"/>
    </ab>
</sp>
<sp>
     <speaker rend="italic">Greg.</speaker>
     <ab>No, for then we should be Colliars.
         <lb n="7" rend="rj"/>
     </ab>
</sp>

完整文件非常大,但可以在这里访问:http: //ota.ox.ac.uk/desc/5721。我正在尝试使用 Python 3 来遍历 xml 并获取与标签关联的所有文本,这是找到对话的地方。

import xml.etree.ElementTree as etree
tree = etree.parse('romeo_juliet_5721.xml')
doc = tree.getroot()
for i in doc.iter(tag='{http://www.tei-c.org/ns/1.0}ab'):   
        print(i.tag, i.text)
>>> http://www.tei-c.org/ns/1.0}ab 
>>>                  
>>> {http://www.tei-c.org/ns/1.0}ab No, for then we should be Colliars.

输出很好地捕获了实体,但没有将“my word wee'l not carry coales”识别为第一个 ab 的文本。如果它在不同的元素中,我看不到它。我考虑过将整个元素转换为字符串并使用正则表达式(或通过剥离所有 xml 标记)获取元素文本,但我宁愿了解这里发生了什么。感谢您的任何帮助,您可以提供。

4

1 回答 1

3

那是因为在ElementTree模型中,文本“my word wee't carry coales”。被认为tail<seg>element 而text不是<ab>。要获取元素的文本及其子元素的尾部,您可以尝试以下方式:

for i in doc.iter(tag='{http://www.tei-c.org/ns/1.0}ab'): 
    innerText = i.text+''.join((text.tail or '') for text in i.iter()).strip()  
    print(i.tag, innerText)
于 2016-05-06T01:58:44.007 回答