我正在写一个if语句,当它选择正确的行时,我希望与它相关联的数据在下面开始两行。
这是我目前的代码:
for l in message.splitlines():
q = l.strip().split(" ")
if q[0] == 'onion-key':
format = ['onion-key']
data = dict(zip(format, q[0:]))
idt= data['onion-key']
print idt
以下是我从中获取信息的字符串:
onion-key
-----BEGIN RSA PUBLIC KEY-----
MIGJAoGBANRir84jtEQP6tqhTubbcs+EWHgzxBdU6QG0HV+3tZ5m4JPo/hTEZd+I
2kvmtYZZ3WdxXhcISkaa476ArbKL6BmPCG1h+yeMko6yhu+gWk/40RE0dHKoPcRg
kV4sXerZezXnB4e1d8FHyDiPmgY6LHvfXZqn19xDRx11/h92/kb5AgMBAAE=
-----END RSA PUBLIC KEY-----
service-key
-----BEGIN RSA PUBLIC KEY-----
MIGJAoGBALVjBUTK0wkWVjh+liiBVrweZskPGiIynKxDy+c4XBnEYqm5dcnifEDf
lgyNxOkv0gwYwrt4gS0+t0fyNARq+u6/MEJCEjgc8aS77gMLy/BQgkQHmLE6adjc
tQCDfklbblobq3YrTCQTgECuG91ol3okMM3M4gYPuGS/7MJmAyonAgMBAAE=
-----END RSA PUBLIC KEY-----
我要做的是选择提到onion-key
的位置,然后在字典中将开始RSA密钥映射到End RSA密钥。
我怎样才能做到这一点?
输出将是一个字典,其中onion-key
是键,值如下:
MIGJAoGBANRir84jtEQP6tqhTubbcs+EWHgzxBdU6QG0HV+3tZ5m4JPo/hTEZd+I
2kvmtYZZ3WdxXhcISkaa476ArbKL6BmPCG1h+yeMko6yhu+gWk/40RE0dHKoPcRg
kV4sXerZezXnB4e1d8FHyDiPmgY6LHvfXZqn19xDRx11/h92/kb5AgMBAAE=
dict{onion-key, MIGJAoGBANRir84jtEQP6tqhTubbcs+EWHgzxBdU6QG0HV+3tZ5m4JPo/hTEZd+I
2kvmtYZZ3WdxXhcISkaa476ArbKL6BmPCG1h+yeMko6yhu+gWk/40RE0dHKoPcRg
kV4sXerZezXnB4e1d8FHyDiPmgY6LHvfXZqn19xDRx11/h92/kb5AgMBAAE=}
答案 0 :(得分:2)
这听起来像正则表达式。
import re
pat=re.compile(r"onion-key\s?-----BEGIN RSA PUBLIC KEY-----\s?(.*?)\s?-----END RSA PUBLIC KEY-----", re.DOTALL)
result = {'onion-key': key for key in pat.findall(message)}
如果您也想找到服务密钥:
pat = re.compile(r"([\w-]+)\s-----BEGIN RSA PUBLIC KEY-----\s(.*?)\s-----END RSA PUBLIC KEY-----", re.DOTALL)
result = dict(pat.findall(message))
或者如果你有一大堆:
results = [dict(pair) for pair in zip(*[iter(pat.findall(message))]*2)]
答案 1 :(得分:0)
f = open('yourfile')
d = {}
for line in f:
line = line.strip()
if line.endswith("-key"):
current_key = line
d[current_key] = ""
elif "-----" not in line:
d[current_key] += line