【问题标题】:handling python networkx keyerror using graphml使用 graphml 处理 python networkx keyerror
【发布时间】:2015-12-11 17:20:56
【问题描述】:

我的 networkx 代码有问题。我正在尝试列出边缘的属性,但我不断收到 KeyError,或者当我尝试捕获错误时,它会跳过整个代码。

背景: 我有一个图表,其边缘表示防火墙规则,具有协议、源端口、目标端口的自定义属性,边缘标签包含操作(允许或拒绝),而边缘之间的节点是源地址和目标地址...... 协议、源和目的端口的默认值是 IP、any、any...

我想做什么: 我试图一一列出所有边缘(规则)及其各自的属性,例如:

Rule has PROTOCOL: tcp    ACTION: allow sPORT: 6667 dPORT: 6667  

问题:在某些情况下,我对协议、源端口和目标端口使用默认值,因此即使我尝试这些值也不会显示

for u,v,n in G.edges_iter(data=True): 
    print ('%s %s %s' % (u,v,n)) 

当我尝试时

print ('Rule has PROTOCOL: %s ACTION: %s sPORT: %s  dPORT: %s' % (n['protocol'],n['label'], n['s_port'], n['d_port']))

我得到了一个KeyError,因为在某些边缘我没有声明协议、s_port 或 d_port。当我尝试在 KeyError 上使用 try 和 except(continue) 时,它会跳出 for 循环并继续执行我的代码的剩余部分。

问题:当边缘属性不可用时,我如何处理 KeyError 或输入诸如“任何”或“无”或“未声明”之类的内容,我希望我的代码打印如下内容:

Rule has PROTOCOL: tcp  ACTION: allow sPORT: any dPORT: any 

当我使用源端口和目标端口的默认值而不是跳过代码时

这是我的代码的样子:

import os
import sys
import string
import networkx as nx

G = nx.read_graphml("fwha.graphml")
count = 0

edges = G.number_of_edges()
nodes = G.number_of_nodes()

print "Number of edges in diagram is: ", edges

for u,v,n in G.edges_iter(data=True):
  try:
    print ('Rule has PROTOCOL:  %s ACTION: %s sPORT: %s dPORT: %s' % (n['protocol'], n['label'], n['s_port'], n['d_port']))
  except KeyError:
    continue

print "Number of nodes in diagram is: ", nodes 
for m,k in G.nodes_iter(data=True):
     print('%s %s' % (k,m))

【问题讨论】:

    标签: python networkx keyerror graphml


    【解决方案1】:

    它只是一个普通的python字典......你可以做一系列的事情,比如

    n.get('protocol', 'any'),
    

    这是很多打字,所以你可以在图形初始化后一次完成:

    for v in G.node:
        G.node[v].setdefault('protocol', 'any')
    

    等等。然后正常走路。

    【讨论】:

    • 感谢 Corley 对您的想法进行了研究,但对其进行了一些调整,并提出了上述完美的答案。
    【解决方案2】:

    好吧,我试过了,尽管它不太整洁并且可以使用函数来整理它,但它现在可以工作了:)

    for u,v,n in G.edges_iter(data=True):
      try: 
        if not n['s_port']:
          print "No Problem here"
      except KeyError: 
          n['s_port'] = 'any'
    
    for u,v,n in G.edges_iter(data=True):
      try:
        if not n['d_port']:
          print "No Problem here"
      except KeyError:
          n['d_port'] = 'any'
     												
    for u,v,n in G.edges_iter(data=True):
      try:
         count = count + 1
         print ('Rule %d - Protocol: %s  Action: %s  SourcePort: %s  Destination Port: %s' % (count,n['protocol'], n['label'], n['s_port'], n['d_port']))
      except KeyError, e:
         count = count+1
         print ('Number %s: It didnt execute and the error is %s' % (count, str(e)))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-23
      • 1970-01-01
      • 2011-07-02
      • 2014-04-10
      • 2016-09-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多