gpt4 book ai didi

python正则表达式拆分字符串,同时保持分隔符与值

转载 作者:太空宇宙 更新时间:2023-11-03 13:20:50 50 4
gpt4 key购买 nike

我正在尝试将其中包含 name:value 元素的文本文件解析为包含“name:value”的列表...这里有一个转折点:值有时会是多个单词甚至是多行,而分隔符不是一组固定的词。这是我正在尝试使用的示例...

listing="price:44.55 name:John Doe title:Super Widget description:This widget slices, dices, and drives your kids to soccer practice\r\nIt even comes with Super Widget Mini!

我要返回的是...

["price:44.55", "name:John Doe", "title:Super Widget", "description:This widget slices, dices, and drives your kids to soccer practice\r\nIt even comes with Super Widget Mini!"]

这是我到目前为止尝试过的...

details = re.findall(r'[\w]+:.*', post, re.DOTALL)
["price:", "44.55 name:John Doe title:Super Widget description:This widget slices, dices, and drives your kids to soccer practice\r\nIt even comes with Super Widget Mini!"]

不是我想要的。或者……

details = re.findall(r'[\w]+:.*?', post, re.DOTALL)
["price:", "name:", "title:", "description:"]

不是我想要的。或者……

details = re.split(r'([\w]+:)', post)
["", "price:", "44.55", "name:", "John Doe", "title:", "Super Widget", "description:", "This widget slices, dices, and drives your kids to soccer practice\r\nIt even comes with Super Widget Mini!"]

哪个更接近,但仍然没有骰子。另外,我可以处理一个空列表项。所以,基本上,我的问题是如何使分隔符与 re.split() 上的值保持一致,或者如何避免 re.findall() 过于贪婪或过于吝啬?

提前感谢阅读!

最佳答案

使用前瞻断言:

>>> re.split(r'\s(?=\w+:)', post)
['price:44.55',
'name:John Doe',
'title:Super Widget',
'description:This widget slices, dices, and drives your kids to soccer practice\r\nIt even comes with Super Widget Mini!']

当然,如果您的值中有一些单词紧跟冒号,它仍然会失败。

关于python正则表达式拆分字符串,同时保持分隔符与值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14715113/

50 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com