python - 如何在 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 转换它的最聪明的方法是什么?
解决方案
您可以使用以下模式:
>>> 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...']
推荐阅读
- c++ - 什么是“不可检测的手段”,它们如何改变 C/C++ 程序的对象?
- python - 如何在后台找到运行 VBScript 的文件位置?
- apache-spark - 在pyspark中计算大型数据帧的所有行之间的余弦相似度
- node.js - Node.js gRPC 库上的 QUIC 协议
- javascript - 无法在 express 中加载 javascript 文件
- python - 如何解决 toml.decoder.TomlDecodeError: Key group not on a line by itself。(第 1 行第 1 列 ...)调用 streamlit 包时出错?
- assembly - 给定两个内存地址,我可以将数据从一个地址移动到另一个地址,而该数据不会进入寄存器
- python - 是否可以使用 Python csv 阅读器读取使用 C++ std::setw 生成的文件?
- flutter - 在初始连接请求时向 IOWebSocketChannel 发送数据
- java - Apache POI 3.16 在 Matlab 中运行时会创建无效文件