gpt4 book ai didi

python - 如何检查lxml元素树字符串?

转载 作者:太空宇宙 更新时间:2023-11-03 15:19:46 25 4
gpt4 key购买 nike

我有一个 lxml 元素树列表。我想在字典中存储子树出现在树列表的任何子树中的次数。例如

tree1='''<A attribute1="1"><B><C/></B></A>'''
tree2='''<A attribute1="1"><D><C attribute="2"/></D></A>'''
tree3='''<E attribute1="1"><B><C/></B></E>'''
list_trees=[tree1,tree2,tree3]
print list_trees
from collections import defaultdict
from lxml import etree as ET
mydict=defaultdict(int)
for tree in list_trees:
root=ET.fromstring(tree)
for sub_root in root.iter():
print ET.tostring(sub_root)
mydict[ET.tostring(sub_root)]+=1
print mydict

我得到以下正确结果:

defaultdict(<type 'int'>, {'<E attribute1="1"><B><C/></B></E>': 1, '<C/>': 2, '<A attribute1="1"><D><C attribute="2"/></D></A>': 1, '<B><C/></B>': 2, '<C attribute="2"/>': 1, '<D><C attribute="2"/></D>': 1, '<A attribute1="1"><B><C/></B></A>': 1})

这只适用于这个特定的例子。然而,在一般情况下,xml 可以是相同的,但具有不同的属性顺序,或者额外的空格或无关紧要的换行符。然而,这种一般情况会破坏我的系统。我知道已经有关于如何检查 2 个相同的 xml 树的帖子,但是,我想将 xml 转换为字符串,以便执行上述特定应用程序(轻松地将唯一的树保留为字符串,以便于比较和更大的灵 active )将来)并且还能够很好地将其存储在sql中。如何将 xml 变成一致的字符串,而不管顺序、多余的空格、多余的行?

编辑给出不起作用的情况:这 3 个 xml 树是相同的,它们只是属性顺序不同或者有额外的空格或换行符。

tree4='''<A attribute1="1" attribute2="2"><B><C/></B></A>'''
tree5='''<A attribute1="1" attribute2="2" >
<B><C/></B></A>'''
tree6='''<A attribute2="2" attribute1="1"><B><C/></B></A>'''

我的输出如下:

defaultdict(<type 'int'>, {'<B><C/></B>': 3, '<A attribute1="1" attribute2="2"><B><C/></B></A>': 1, '<A attribute1="1" attribute2="2">\n<B><C/></B></A>': 1, '<C/>': 3, '<A attribute2="2" attribute1="1"><B><C/></B></A>': 1})

但是,输出应该是:

defaultdict(<type 'int'>, {'<B><C/></B>': 3, '<A attribute1="1" attribute2="2"><B><C/></B></A>': 3, '<C/>': 3})

最佳答案

如果您坚持比较 XML 树的字符串表示形式,我建议使用 BeautifulSoup在 lxml 之上。特别是,在树的任何部分调用 prettify() 都会创建一个独特的表示,忽略输入中的空格和奇怪的格式。输出字符串有点冗长,但它们可以工作。我继续将换行符替换为“假换行符”('\n' -> '\\n'),以便输出更加紧凑。

from collections import defaultdict
from bs4 import BeautifulSoup as Soup

tree4='''<A attribute1="1" attribute2="2"><B><C/></B></A>'''
tree5='''<A attribute1="1" attribute2="2" >
<B><C/></B></A>'''
tree6='''<A attribute2="2" attribute1="1"><B><C/></B></A>'''
list_trees = [tree4, tree5, tree6]

mydict = defaultdict(int)
for tree in list_trees:
root = Soup(tree, 'lxml-xml') # Use the LXML XML parser.
for sub_root in root.find_all():
print(sub_root)
mydict[sub_root.prettify().replace('\n', '\\n')] += 1

print('Results')
for key, value in mydict.items():
print(u'%s: %s' % (key, value))

打印出所需的结果(带有一些额外的换行符和空格):

$ python 计数器.py

<A attribute1="1" attribute2="2">\n <B>\n  <C/>\n </B>\n</A>: 3
<B>\n <C/>\n</B>: 3
<C/>\n: 3

关于python - 如何检查lxml元素树字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43627350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com