我正在使用 xml.etree.ElementTree
来解析 XML 文件。我有个问题。我不知道如何获取标签之间的纯文本行。
<Sync time="4.496"/>
<Background time="4.496" type="music" level="high"/>
<Event desc="pause" type="noise" extent="instantaneous"/>
Plain text
<Sync time="7.186"/>
<Event desc="b" type="noise" extent="instantaneous"/>
Plain text
<Sync time="10.949"/>
Plain text
我已经有了这个代码:
import xml.etree.ElementTree as etree
import os
data_file = "./file.xml"
xmlD = etree.parse(data_file)
root = xmlD.getroot()
sections = root.getchildren()[2].getchildren()
for section in sections:
turns = section.getchildren()
for turn in turns:
speaker = turn.get('speaker')
mode = turn.get('mode')
childs = turn.getchildren()
for child in childs:
time = child.get('time')
opt = child.get('desc')
if opt == 'es':
opt = "ESP:"
elif opt == "la":
opt = "LATIN:"
elif opt == "*":
opt = "-ININT-"
elif opt == "fs":
opt = "-FS-"
elif opt == "throat":
opt = "-THROAT-"
elif opt == "laugh":
opt = "-LAUGH-"
else:
opt = ""
print speaker, mode, time, opt+child.tail.encode('latin-1')
我可以通过 XML 访问 Sync|Background|Event 标记之前的内容,但无法提取这些标记之后的文本。我放置了 XML 文件的一部分,而不是整个文件。我只对最后一段代码有问题
非常感谢@alecxe。现在我可以获得我需要的信息。但现在我有一个新的小问题。我获得了键入 tail
命令的行,但之前生成了换行符 \n
或类似的内容,因此,我需要类似的内容:
spk1计划的LAN:来自尾部的纯文本
>
但我明白了:
spk1 规划的 LAN:
尾部纯文本
我在处理XML后尝试了很多东西,re.match()
模块,sed
命令,但似乎没有\n
新行字符,但我无法“放置”纯文本!预先感谢您
有人吗?谢谢!
最佳答案
这称为 tail
of an element :
The tail attribute can be used to hold additional data associated with the element. This attribute is usually a string but may be any application-specific object. If the element is created from an XML file the attribute will contain any text found after the element’s end tag and before the next tag.
找到Event
标签并获取尾部,例如:
section.find("Event").tail
关于python - 解析 XML Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30166240/