gpt4 book ai didi

python - 将 GraphML 文件转换为另一个文件

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

您好,我有一个简单的 graphML 文件,我想从 GraphML 中删除节点标记并将其保存在另一个 GraphML 文件中。 GraphML 大小为 3GB,下面给出的是示例。

输入文件:

<?xml version="1.0" ?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.1/graphml.xsd">
<key id="weight" for="edge" attr.name="weight" attr.type="string"></key>
<graph id="G" edgedefault="directed">
<node id="1"></node>
<node id="2">
</node>
<node id="3">
</node>
<node id="4">
</node>
<node id="5">
</node>
<edge id="6" source="1" target="2">
<data key="weight">3</data>
</edge>
<edge id="7" source="2" target="4">
<data key="weight">1</data>
</edge>
<edge id="8" source="2" target="3">
<data key="weight">9</data>
</edge>
</graph>
</graphml>

所需输出:

<?xml version="1.0" ?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.1/graphml.xsd">
<key id="weight" for="edge" attr.name="weight" attr.type="string"></key>
<graph id="G" edgedefault="directed">
<edge id="6" source="1" target="2">
<data key="weight">3</data>
</edge>
<edge id="7" source="2" target="4">
<data key="weight">1</data>
</edge>
<edge id="8" source="2" target="3">
<data key="weight">9</data>
</edge>
</graph>
</graphml>

有什么方法可以做到这一点吗?

最佳答案

有一个Python模块来处理graphml。奇怪的是,documentation没有removedelete功能。

由于 graphml 是 xml 标记,因此您可以改用 xml 模块。我用过xmltodict并且非常喜欢它。该模块允许您将 xml 代码加载到 python 对象中。修改对象后,可以将其保存回xml。

如果data是包含xml的字符串:

data_object=xmltodict.parse(data)
del data_object["graphml"]["graph"]["node"]
xmltodict.unparse(data_object, pretty=True)

这会删除 node 条目,解解析将返回带有 xml 的字符串。

如果 xml 的结构变得更加复杂,您将需要在 data_object 中搜索节点。但这应该不是问题,它只是一个有序的字典。

另一个问题可能是 xml 的大小。 3GB很多了。xmltodict 确实支持大文件的流模式,但这是我从未使用过的。

关于python - 将 GraphML 文件转换为另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41735778/

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