首页 > 解决方案 > 如何在 Python 中根据带点的数字分割文本?

问题描述

我有以下简单的文字:

2 of 5 deliveries some text some text... 1. 3 of 5 items some text some text... 2. 1 of 5 items found in box some text...

现在我希望根据数字 [0.-9.] 将文本拆分如下:(每行代表列表中的条目)。

2 of 5 deliveries some text some text...,
3 of 5 items some text some text...,
1 of 5 items found in box some text...

这是所需的输出。但是,它并不能真正与with 一起regex使用re.split('([0\.-9\.]+)', text)。它总是只用数字分隔。用 Python 转换它的最聪明的方法是什么?

标签: pythonstringnlp

解决方案


您可以使用以下模式:

>>> re.split(r'\s+\d+\.\s+', text)
['2 of 5 deliveries some text some text...',
 '3 of 5 items some text some text...',
 '1 of 5 items found in box some text...']

解释:

>>> re.split(r'''
        \s+        # Matches leading spaces to the separator
        \d+        # Matches digit character
        \.         # Matches '.' character
        \s+        # Matches trailing spaces after the separator
        ''', text, flags=re.VERBOSE)

['2 of 5 deliveries some text some text...',
 '3 of 5 items some text some text...',
 '1 of 5 items found in box some text...']

推荐阅读