我正在尝试使用以下代码从 tei 文件中提取一些信息:
tree = ET.parse(path)
root = tree.getroot()
body = root.find("{http://www.tei-c.org/ns/1.0}text/{http://www.tei-c.org/ns/1.0}body")
for s in body.iter("{http://www.tei-c.org/ns/1.0}s"):
for w in s.iter("{http://www.tei-c.org/ns/1.0}w"):
wordpart = w.find("{http://www.tei-c.org/ns/1.0}seg")
word = ''.join(wordpart.itertext())
type = w.get('type')
xml = w.get('xml:id')
print(type)
print(xml)
type
的输出是正确的,它打印例如“名词”。但对于 xml:id
我只能得到 None
。这是我需要解析的 xml 文件的摘录:
<w type="noun" xml:id="w.4940"><seg type="orth">sloterheighe</seg>...
最佳答案
要获取 xml:id
属性的值,您需要像这样指定命名空间 URI(有关更多详细信息,请参阅 this SO post):
xml = w.attrib['{http://www.w3.org/XML/1998/namespace}id']
或
xml = w.get('{http://www.w3.org/XML/1998/namespace}id')
另外,请注意 type
是 Python 中的内置方法,因此请避免将其用作变量名称。
关于Python 属性解析对于 xml :id 返回 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55918959/