使用Python提取文件中两个大括号之间的信息
我有一个以 JSON 结构编写的文件,但格式不正确。内容看起来与此类似:
[{"key0":"value0" , "key1":"value1", "key2":"value2"}, {"key0":"value3", "key1":"value4", "key2:"value5"}, {"key0":"value6", "key1":"value7", "key2:"value8"}]
与之前提出的许多问题不同,内容都在同一行,所以我试图逐行读取代码,但如果我使用 readline(),我会选择整个内容。
我试图仅提取大括号 { } 和方括号之间的信息,然后打印它们。我能够打开该文件,但我发现很难找到一种方法从 { 开始读取并以 } 结束,然后继续查找下一个 { 和 } 等等。我并不关心方括号,只关心大括号。 此外,这些值的长度可以不同,因此我可以设置要在括号后读取的字符数,因为大多数时候每组括号的字符数都是不同的。
任何指导将不胜感激。
I have a file that was written in a JSON structure but is not correctly formatted. The content looks similar to this:
[{"key0":"value0" , "key1":"value1", "key2":"value2"}, {"key0":"value3", "key1":"value4", "key2:"value5"}, {"key0":"value6", "key1":"value7", "key2:"value8"}]
Unlike many questioned asked here before, the contents are all on the same line, so I was trying to read the code line by line but I select the whole thing if I use readline().
I am trying to extract only the information between the curly brackets { } with the brackets, and print them. I am able to open the file, but I am finding it difficult to find a way to read starting from the { and ending at } then continue to look for the next { and } and so on. I don't really care about the square brackets, just the curly brackets.
Also, the values can differ in length so I can set a number of characters to be read after the bracket, as it is different for each set of brackets most of the time.
Any guidance would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我建议您使用 regex 模块来修改这些行,然后将它们转换为字典:
在您的示例中,运行上面的代码将导致类似的结果:
此外,您将可以访问该字典的键和值。
注意上面代码中的“data.txt”文件如下:
I suggest you use the regex module in order to modify the lines and then transform them into a dictionary:
In your example, running the code above would result in something like:
Moreover, you will have access to the keys and values of this dictionary.
Note that the "data.txt" file in the code above is as follows:
尝试使用 Python 中的 json.loads 方法 json 编码器模块,将 fp(支持 .read() 的文本文件或包含
JSON
文档的二进制文件)反序列化为使用转换的 Python 对象表”。解码 json 字符串:
输出:
值8
Try using
json.loads
method fromPython
json encoder module that "Deserialize fp (a .read()-supporting text file or binary file containing aJSON
document) to a Python object using a conversion table".To decode your json string:
output:
value8