我需要解析如下所示的文本文件:
key : 123
anotherKey : qwer
oneMoreKey :
somestring,
somestring 有很多这种类型的字符串,它们是由服务器自动生成的,所以我不知道它们中有多少会收到解析器
我已经解决了foo : bar这样的解析问题:
def main():
data = {}
file = open('file.txt') # opening log file
for line in file:
if re.match(r'^\s*$', line):
pass
else:
line = line.split(':')
key = line[0].strip()
if len(line) == 2: # this is a workaround for lines like "foo :\n
value = line[1].strip()
else:
value = 'none'
if key in data:
pass
else:
data[key] = value 我需要获取json中的所有数据,比如
{
key : 123,
anotherKey : qwer,
oneMoreKey : [somestring, somestring]
}发布于 2019-02-10 18:16:35
某些事。是像这样吗?
import re
rx = re.compile(r'^(?P<key>\w+)\s:(?P<value>.+?)(?=^\w+\s*:|\Z)', re.S | re.M)
junk = """key : 123
anotherKey : qwer
foo : bar, zxc
oneMoreKey :
somestring,
somestring
"""
def match(m):
values = [val for value in re.split(r', *[\n\r]+', m) for val in [value.strip()] if val]
return values if len(values) > 1 else m.strip()
d = {m.group('key'): match(m.group('value')) for m in rx.finditer(junk)}
print(d)这会产生
{'key': '123', 'anotherKey': 'qwer', 'foo': 'bar, zxc', 'oneMoreKey': ['somestring', 'somestring']}https://stackoverflow.com/questions/54619406
复制相似问题