使用python对文件中给定的模式执行regex操作

2024-05-28 15:38:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在读取一个包含60K JSON的文件,格式如下:

{ "log": [
       {"code": "abc",
         "refs": ["a":"b"]
       }
]}
{ "log": [
       {"code": "xyz",
         "refs": ["p":"q", "x": ["abc","xyz"] ]
       }
]}

我需要使用regex执行3个操作:

1. "[" at start of file
2.  "]" at the end of file
3. Find pattern: ]}{ "log": [  and add comma in it ]},{ "log": [ 

注意:该模式在每个字符之间有空行和空格。此模式中不存在其他特殊字符或字母

我的输出文件应该是:

[{ "log": [
       {"code": "abc",
         "refs": ["a":"b"]
       }
]},
{ "log": [
       {"code": "xyz",
         "refs": ["p":"q", "x": ["abc","xyz"] ]
       }
]}]

Python代码:

f = open('C:/Users/Desktop/SampleTestFiles/logfile.json',"r+")
s = f.read()
s = '[' + s + ']' # This does not works. Brackets are added to end of file.

Tags: 文件oflogjson格式模式codestart
1条回答
网友
1楼 · 发布于 2024-05-28 15:38:45

对于一个文本文件包含多个简单地连接在一起的JSON对象的情况(即,没有将它们放入列表中,因此在JSON编码的对象之间缺少,),下面的内容可能有助于纠正这一问题(不会解释其他地方的错误编码;问题的输入已修改为仅针对提问者要求的内容):

>>> import re
>>> import json
>>> s = """
... { "log": [
...        {"code": "abc",
...          "refs": {"a":"b"}
...        }
... ]}
... { "log": [
...        {"code": "xyz",
...          "refs": {"p":"q", "x": ["abc","xyz"] }
...        }
... ]}
... 
... 
... { "log": [
...        {"code": "abc",
...          "refs": {"a":"b"}
...        }
... ]}
... """
>>> items = json.loads('[' + re.sub('}\s*{', '},\n{', s, flags=re.M) + ']')
>>> items[0]
{'log': [{'code': 'abc', 'refs': {'a': 'b'}}]}
>>> items[1]
{'log': [{'code': 'xyz', 'refs': {'p': 'q', 'x': ['abc', 'xyz']}}]}
>>> items[2]['log'][0]['code']
'abc'

关键位是re.sub('}\s*{', '},\n{', s, flags=re.M),表达式所做的('}\s*{')是查找}{的所有情况,这些情况仅由空格隔开(或者完全没有)。另一位是flags关键字参数,以确保跨多行检查替换,否则表达式将像原始示例一样跨换行匹配

相关问题 更多 >

    热门问题