我有这样的数据:
(asn,prefix,ip,count_domain)
(15967, '77.55.0.0/16', '77.55.236.177', 10)
(15967, '77.55.0.0/16', '77.55.236.178', 11)
(20773, '195.225.104.0/22', '195.225.104.182', 22)
(20773, '195.225.104.0/22', '195.225.104.181', 10)
(8560, '87.106.0.0/16', '87.106.1.10', 15)
(20454, '198.24.128.0/19', '198.24.143.43', 89)
(20454, '198.24.128.0/19', '198.24.143.45', 608)
(20454, '198.24.128.0/19', '198.24.143.46', 32)
(31815, '216.70.96.0/20', '216.70.102.229', 12)
(31815, '216.70.96.0/20', '216.70.102.228', 20)
我希望每个asn和前缀提取一些ips和域名,如下所示:
(asn,prefix,count_ip,count_domain)
(15967, '77.55.0.0/16', 2, 21)
(20773, '195.225.104.0/22', 2, 32)
(8560, '87.106.0.0/16', 1, 15)
(20454, '198.24.128.0/19', 3, 729)
(31815, '216.70.96.0/20', 2, 32)
我当前的python脚本是这样但我在字典中输入错误的语法错误。有人可以帮忙吗?
count = {}
with open (output,'w') as w:
with open (file , 'r') as f:
for line in f :
if line.strip() != '':
domain = int(line.split('|')[1])
if domain>=10:
ip = line.split('|')[0]
try:
prefix = asndb.lookup(ip)[1]
asn = asndb.lookup(ip)[0]
if [asn,prefix] not in count:
count[asn,prefix] = count
else:
count[asn,prefix] += count
# print(asn,prefix,ip,domain)
except:
print line
pass
ERROR:
if asn,prefix not in count:
^
SyntaxError: invalid syntax
答案 0 :(得分:3)
明确指定一个元组,其值为asn
和prefix
,然后使用元组作为键(我认为这是您尝试做的事情,基于标题)。此外,如果您按照我认为您正在使用它的方式使用字典,请将计数增加1(而不是尝试将字典的引用指定为值)。
prefix = asndb.lookup(ip)[1]
asn = asndb.lookup(ip)[0]
key = (asn, prefix)
if key not in count:
count[key] = 1
else:
count[key] += 1
编辑修复@AshwiniChaudhary发现的愚蠢错字
答案 1 :(得分:1)
if [asn,prefix] not in count:
列表类型不能是dict的关键。