如何将带有某些正则表达式的文本转换成Dictionares? -Python

问题描述 投票:-1回答:1

来自:[email protected]

用户代理:Thunderbird 1.5.0.9(X11 / 20061227)

MIME版本:1.0

收件人:[email protected]

python regex dictionary
1个回答
0
投票

[不知道真正的格式是什么,似乎不需要正则表达式。

相反,这样的例子适用于您的示例:

text = """
From: [email protected]
User-Agent: Thunderbird 1.5.0.9 (X11/20061227)
MIME-Version: 1.0
To: [email protected]
""".strip()

out_dict = dict(
  line.split(": ")
  for line in text.split("\n")
)

print(out_dict)

这假设遇到的唯一可能的':'在键和值之间。如果您的文本不是这种情况,则可以迭代直到遇到第一个:然后停止。

© www.soinside.com 2019 - 2024. All rights reserved.