因此,我有一个与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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句