得到一段代码,应该搜索一个文件,看看它是否包含搜索阶段,然后返回分配给它的数据,但是它总是返回无,即使它在文件中,我也看不清楚为什么会失败
r Goblin500 IspSUjBIQ/LJ0k18VbKIO6mS1oo gorgBf6uW8d6we7ARt8aA6kgiV4 2014-08-12 06:11:58 82.26.108.68 9001 9030
s Fast HSDir Running V2Dir Valid
v Tor 0.2.4.23
w Bandwidth=21
p reject 1-65535
是我想要阅读的代码行
这就是我试图找到价值的方式:
def getRouter(nm):
for r in router.itervalues():
if r['nick'] == nm:
return r
return None
print getRouter("Goblin500")
这就是文件内容如何将共识解析成dict:
# Parse the consensus into a dict
for l in consensus_txt.splitlines():
q = l.strip().split(" ")
if q[0] == 'r': #router descriptor
rfmt = ['nick', 'identity', 'digest', 'pubdate', 'pubtime', 'ip', 'orport', 'dirport']
data = dict(zip(rfmt, q[1:]))
idt= data['identity']
idt += "=" * (4-len(idt)%4) # pad b64 string
ident = data['identity'] = base64.standard_b64decode(idt)
data['identityhash'] = binascii.hexlify(ident)
data['identityb32'] = base64.b32encode(ident).lower()
router[ident] = data
curRouter = ident
if q[0] == 's': #flags description - add to tally totals too
router[curRouter]['flags'] = q[1:]
for w in q[1:]:
if flags.has_key(w):
flags[w]+=1
else:
flags[w] = 1
total += 1
if q[0] == 'v':
router[curRouter]['version'] = ' '.join(q[1:])
我错过了什么?
感谢
答案 0 :(得分:0)
原始字符串解析时出错。这可以防止您以后匹配这些值。 Sample code that proves the parsing is wrong:
q = 'r Goblin500 IspSUjBIQ/LJ0k18VbKIO6mS1oo gorgBf6uW8d6we7ARt8aA6kgiV4 2014-08-12 06:11:58 82.26.108.68 9001 9030'
rfmt = ['nick', 'identity', 'digest', 'pubdate', 'pubtime', 'ip', 'orport', 'dirport']
data = dict(zip(rfmt, q[1:]))
print(data)
# {'pubdate': 'b', 'dirport': '5', 'ip': 'i', 'orport': 'n', 'nick': ' ', 'identity': 'G', 'digest': 'o', 'pubtime': 'l'}
print(data['nick'])
# prints out a single space
基本上,q[1:]
语句的zip
部分只是抓取字符串的第一个字符。我认为你想要的是q.split()[1:]
。这将在空格上拆分字符串,将其转换为列表,然后忽略第一个元素。