3 回答
TA贡献1815条经验 获得超13个赞
代替re.findall,您可以使用re.split以字母和数字为界的空格分割字符串:
import re
d = ['avg yearly income 25,07,708.33 ', 'current balance 1,25,000.00 in cash\n', 'target savings 50,00,000.00 within next five years 1,000,000.00 ']
final_results = [re.split('(?<=[a-zA-Z])\s(?=\d)|(?<=\d)\s(?=[a-zA-Z])', i) for i in d]
new_results = [[i.rstrip() for i in b] for b in final_results]
输出:
[['avg yearly income', '25,07,708.33'], ['current balance', '1,25,000.00', 'in cash'], ['target savings', '50,00,000.00', 'within next five years', '1,000,000.00']]
TA贡献1851条经验 获得超4个赞
您可以re.split与ptrn一起使用r'(?<=\d)\s+(?=\w)|(?<=\w)\s+(?=\d)'
>>> ptrn = r'(?<=\d)\s+(?=\w)|(?<=\w)\s+(?=\d)'
>>> re.split(ptrn, a)
['avg yearly income', '25,07,708.33 ']
>>> re.split(ptrn, b)
['current balance', '1,25,000.00', 'in cash\n']
>>> re.split(ptrn, c)
['target savings', '50,00,000.00', 'within next five years', '1,000,000.00 ']
TA贡献1811条经验 获得超6个赞
使用re.split(); 这个例子使用你原来的正则表达式,它工作正常:
>>> r = re.compile(r'(\d+(?:,\d+)*(?:\.\d{1,2}))')
>>> r.split('avg yearly income 25,07,708.33 ')
['avg yearly income ', '25,07,708.33', ' ']
>>> r.split('current balance 1,25,000.00 in cash\n')
['current balance ', '1,25,000.00', ' in cash\n']
>>> r.split('target savings 50,00,000.00 within next five years 1,000,000.00 ')
['target savings ', '50,00,000.00', ' within next five years ', '1,000,000.00', ' ']
添加回答
举报