use*_*403 3 python xml xml-parsing
我有很多包含大量文本的xml文件.本文我需要做小写并删除标点符号.但我不知道怎么说使用python,我希望它忽略所有的标签.
我发现了一个名为ElementTree的xml解析器,我有一个正则表达式来查找标签:
pattern = re.compile ('<[^<]*?>')
我测试了它,它只给我第一个标签中的文本(有许多标签命名).为什么?
我在一个字符串中测试以进行不同的测试,以获得所有标记:
text = "<root> <test>aaaaaaa </test> <test2> bbbbbbbbb </test2> </root> <root> <test3> cccccc </test3> <test4> ddddd </test4> </root>"
pattern = re.compile ('<[^<]*?>')
tmp = pattern.findall(content, re.DOTALL)
Run Code Online (Sandbox Code Playgroud)
它给了我:
['</test>', '<test2>', '</test2>', '</root>', '<root>', '<test3>', '</test3>', '<test4>', '</test4>', '</root>']
Run Code Online (Sandbox Code Playgroud)
为什么不<root> <test>呢?
您实际上似乎没有使用ElementTree.
以下是如何使用ElementTree的示例
import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()
Run Code Online (Sandbox Code Playgroud)
您可以使用递归通过函数运行所有标记来清理它们:
def clean_tag(tag):
for child in tag:
clean_tag(child)
if tag.text != None:
# add your code to do lowercase and punctuation here
tag.text = tag.text.lower()
clean_tag(tree.getroot())
clean_xml = ET.tostring(tree)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
897 次 |
| 最近记录: |