如何在python中使用split from regex并保留split单词?

2024-05-20 22:17:19 发布

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

有没有一种方法可以在不丢失用于拆分的单词或字符的情况下使用拆分函数?你知道吗

例如:

import re
x = '''\
1.
abcde.
2.
fgh 2.5 ijk.
3.
lmnop
    '''
print(x)

listByNum = re.split(r'\d\.\D', x)

print(listByNum) 

the output 我想把数字留在名单上

另一个例子:

import re
x = '''\
I love stackoverflow. I love food.\nblah blah blah.
    '''
print(x)

listBySentences = re.split(r'\.', x)

print(listBySentences)

output for example 2


Tags: 方法函数importre情况字符单词split
1条回答
网友
1楼 · 发布于 2024-05-20 22:17:19

没有很好的文档记录,但是可以在有问题的表达式周围使用括号:

import re
x = '''\
1.
abcde.
2.
fgh 2.5 ijk.
3.
lmnop
    '''
print(x)

listByNum = re.split(r'(\d\.\D)', x)

print(listByNum) 
# ['', '1.\n', 'abcde.\n', '2.\n', 'fgh 2.5 ijk.\n', '3.\n', 'lmnop\n    ']


要在事后清理数据,可以使用列表理解,如下所示:
listByNum = [num.strip() for num in re.split(r'(\d\.\D)', x) if num]
# ['1.', 'abcde.', '2.', 'fgh 2.5 ijk.', '3.', 'lmnop']


要将数字保留在拆分的元素中,可以使用较新的regex模块,该模块支持对空字符串进行拆分:
import regex as re
x = same string as above
listByNum = [num.strip() for num in re.split(r'(?V1)(?=\d\.\D)', x) if num]
# ['1.\nabcde.', '2.\nfgh 2.5 ijk.', '3.\nlmnop']

相关问题 更多 >