Python 3.x 如何使用正则表达式拆分具有特殊模式的字符串并将其保存到python中的列表中
我有这样一个字符串:Python 3.x 如何使用正则表达式拆分具有特殊模式的字符串并将其保存到python中的列表中,python-3.x,regex,Python 3.x,Regex,我有这样一个字符串: '{"po": 118.0, "count": 1.0}, {"po": 124.0, "count": 1.0}, {"po": 132.0, "count": 2.0}' 我想拆分此字符串并使用python将其保存到如下列表中: ['{"po": 118.0, "count": 1.0}', '{"
'{"po": 118.0, "count": 1.0}, {"po": 124.0, "count": 1.0}, {"po": 132.0, "count": 2.0}'
我想拆分此字符串并使用python将其保存到如下列表中:
['{"po": 118.0, "count": 1.0}', '{"po": 124.0, "count": 1.0}', '{"po": 132.0, "count": 2.0}']
当我这样做时:
r=re.split(r"['{}']", s)
但我收到的结果不是我想要的:
['', '"po": 118.0, "count": 1.0', ', ', '"po": 124.0, "count": 1.0', ', ', '"po": 132.0, "count": 2.0', '']
请您指导我如何使用正则表达式拆分字符串好吗
非常感谢您提供的任何帮助。这看起来很像一些JSON内容的片段,如果是这样,您可能希望使用原始的有效JSON。如果您必须从当前出发点出发,那么我建议您在此处使用
re.findall
:
inp='{“po”:118.0,“count”:1.0},{“po”:124.0,“count”:1.0},{“po”:132.0,“count”:2.0}'
output=re.findall(r'\{.*.\}',inp)
打印(输出)
这张照片是:
['{"po": 118.0, "count": 1.0}', '{"po": 124.0, "count": 1.0}', '{"po": 132.0, "count": 2.0}']
['{"po": 118.0, "count": 1.0}', '{"po": 124.0, "count": 1.0}', '{"po": 132.0, "count": 2.0}']
假设您的输入没有任何嵌套内容,这种方法应该很好。这看起来很像某个JSON内容的片段,如果是,那么您可能希望使用原始的有效JSON。如果您必须从当前出发点出发,那么我建议您在此处使用
re.findall
:
inp='{“po”:118.0,“count”:1.0},{“po”:124.0,“count”:1.0},{“po”:132.0,“count”:2.0}'
output=re.findall(r'\{.*.\}',inp)
打印(输出)
这张照片是:
['{"po": 118.0, "count": 1.0}', '{"po": 124.0, "count": 1.0}', '{"po": 132.0, "count": 2.0}']
['{"po": 118.0, "count": 1.0}', '{"po": 124.0, "count": 1.0}', '{"po": 132.0, "count": 2.0}']
假设您的输入没有任何嵌套内容,这种方法应该可以。请尝试以下方法:
import re
str = '{"po": 118.0, "count": 1.0}, {"po": 124.0, "count": 1.0}, {"po": 132.0, "count": 2.0}'
r = re.split(r'(?<=}),\s*(?={)', str)
print(r)
请您尝试以下方法:
import re
str = '{"po": 118.0, "count": 1.0}, {"po": 124.0, "count": 1.0}, {"po": 132.0, "count": 2.0}'
r = re.split(r'(?<=}),\s*(?={)', str)
print(r)