Python从documen中剥离XML标记

2024-04-27 13:04:15 发布

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

我正在尝试使用Python(一种我是新手的语言)从文档中剥离XML标记。这是我第一次尝试使用regex,这是我对最佳方案的一个希望。

mfile = file("somefile.xml","w")

for line in mfile:
    re.sub('<./>',"",line) #trying to match elements between < and />

失败得很惨。我想知道如何处理正则表达式。

其次,我搜索了一下发现:http://code.activestate.com/recipes/440481-strips-xmlhtml-tags-from-string/

这似乎有效。但是,我想知道有没有一种更简单的方法来去掉所有的xml标记?也许用元素树?


Tags: in文档标记re语言forline方案
3条回答

不需要lxml外部库就可以替代耶利米的回答:

import xml.etree.ElementTree as ET
...
tree = ET.fromstring(Text)
notags = ET.tostring(tree, encoding='utf8', method='text')
print(notags)

应适用于任何Python>;=2.5

Please, note, that usually it is not normal to do it by regular expressions. See Jeremiah answer.

试试这个:

import re

text = re.sub('<[^<]+>', "", open("/path/to/file").read())
with open("/path/to/file", "w") as f:
    f.write(text)

最可靠的方法可能是使用LXML

from lxml import etree
...
tree = etree.parse('somefile.xml')
notags = etree.tostring(tree, encoding='utf8', method='text')
print(notags)

它将避免用正则表达式“解析”XML的问题,并且应该正确地处理转义和所有事情。

相关问题 更多 >