python - 将文本转换为键值对
问题描述
给定这样的文本:
"$key\n
some value\n
$another_key\n
another longer\n
value\n"
# continue this trend with keys on lines marked by special symbol in this case $
# with corresponding value on the following lines until we hit another key
将它转换成这样的列表会有什么好的和简洁的方法
keys = ["$key", "$another_key"]
values = ["some value", "another longervalue"]
解决方案
您可以在行首使用 $ 来识别这是一个新键,将其附加到键列表中,并将新的空白字符串附加到值列表中。然后,每次您有一行不以 $ 开头时,您将该值连接到值的最后一个元素,因为该行必须与当前键相关。只有当您读取一个新键时,您才会创建一个新的空白值元素。
data = "$key\nsome value\n$another_key\nanother longer\nvalue\n"
keys = []
values = []
for line in data.split('\n'):
if line.startswith('$'):
keys.append(line)
values.append("")
else:
values[-1] += line
print(keys, values)
输出
['$key', '$another_key'] ['some value', 'another longervalue']
推荐阅读
- java - Smack XMPP Java:如何访问 ByteStreamRequest (OPEN) 的原始 XML 表示?
- c# - 如果使用 PSExec 运行 .exe 文件,则访问被拒绝,如果在没有 PSExec 的情况下运行,则被批准
- python - 如何在python中成为int数组?
- php - 如何访问使用表单构建器构建的表单的 POST 字段?
- python-3.x - 运行 train.py 或 model_main.py 时出现未知错误
- ios - 每次点击按钮时执行一个方法
- javascript - 从随机字符串中删除非数字字符,除了第一次出现#
- java - Java中是否有一种方法可以用给定的字符串替换第一次出现的字符串?
- javascript - 在生产中捕获浏览器 Javascript 异常并发送通知
- c - 在数组中插入 char 数组元素由 char 数组组成