在python中解析包含强调标记的xml文件

2024-06-28 11:02:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在编写一个python脚本,可以提取xml文件中的所有文本。我正在使用元素树库来解释数据,但是我遇到了这个问题,但是当数据是这样构造的

<Segment StartTime="639.752" EndTime="642.270" Participant="fe016">
  But I bet it's a good <Pause/> superset of it.
</Segment>

当我试着读课文时,我会在暂停标记之前看到段的前半部分(“好的,我们所看到的”)

我想弄清楚的是,是否有一种方法可以忽略数据段中的标记并打印出所有文本


Tags: 文件数据标记文本脚本元素segmentit
2条回答
xml = '''<Segment StartTime="639.752" EndTime="642.270" Participant="fe016">
  But I bet it's a good <Pause/> superset of it.
</Segment>'''

# solution using ETree
from xml.etree import ElementTree as ET

root = ET.fromstring(xml)
pause = root.find('./Pause')
print(root.text + pause.tail)

另一个解决方案

from simplified_scrapy import SimplifiedDoc,req,utils
html = '''<Segment StartTime="639.752" EndTime="642.270" Participant="fe016">
  But I bet it's a good <Pause/> superset of it.
</Segment>'''
doc = SimplifiedDoc(html)
print(doc.Segment)
print(doc.Segment.text)

结果:

{'StartTime': '639.752', 'EndTime': '642.270', 'Participant': 'fe016', 'tag': 'Segment', 'html': "\n  But I bet it's a good <Pause /> superset of it.\n"}
But I bet it's a good superset of it.

这里有更多的例子https://github.com/yiyedata/simplified-scrapy-demo/blob/master/doc_examples

相关问题 更多 >