所以我有一个类似于 JSON 格式的键值文件,但它的不同之处足以让 Python JSON 解析器无法获取。
示例:
"Matt"
{
"Location" "New York"
"Age" "22"
"Items"
{
"Banana" "2"
"Apple" "5"
"Cat" "1"
}
}
是否有任何简单的方法来解析此文本文件并将值存储到数组中,以便我可以使用类似于 Matt[Items][Banana] 的格式访问数据?每行只能有一对,括号应表示下一级和上一级。
最佳答案
您可以使用re.sub
“修复”你的字符串然后解析它。只要格式始终是每行上的单引号字符串或一对引号字符串,您就可以使用它来确定放置逗号和冒号的位置。
import re
s = """"Matt"
{
"Location" "New York"
"Age" "22"
"Items"
{
"Banana" "2"
"Apple" "5"
"Cat" "1"
}
}"""
# Put a colon after the first string in every line
s1 = re.sub(r'^\s*(".+?")', r'\1:', s, flags=re.MULTILINE)
# add a comma if the last non-whitespace character in a line is " or }
s2 = re.sub(r'(["}])\s*$', r'\1,', s1, flags=re.MULTILINE)
完成此操作后,您可以使用 ast.literal_eval
将其转换为 Python 字典。我在 JSON 解析上使用它,因为它允许尾随逗号,如果没有逗号,决定在哪里放置逗号会变得更加复杂:
import ast
data = ast.literal_eval('{' + s2 + '}')
print data['Matt']['Items']['Banana']
# 2
关于python - 在Python中解析键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33071319/