【问题标题】:Split a string with where number comes用数字来分割一个字符串
【发布时间】:2019-05-24 04:32:56
【问题描述】:

我有这个字符串

a = "IN 744301 Mus Andaman & Nicobar Islands   01  Nicobar 638 Carnicobar 9.2333  92.7833 4"

我想用正则表达式分割这个数字,输出会是这样的

['IN' , '744301', 'Mus Andaman & Nicobar Islands', '01' , 'Nicobar', '638', 'Carnicobar', '9.2333','92.7833', '4' ]

【问题讨论】:

  • 到目前为止你尝试了什么?

标签: python string split


【解决方案1】:

您可以使用前瞻和后瞻:

import re
a = "IN 744301 Mus Andaman & Nicobar Islands   01  Nicobar 638 Carnicobar 9.2333  92.7833 4"
new_a = re.split('(?<=\d)\s+|\s+(?=\d)', a)

输出:

['IN', '744301', 'Mus Andaman & Nicobar Islands', '01', 'Nicobar', '638', 'Carnicobar', '9.2333', '92.7833', '4']

正则表达式解释:

(?&lt;=\d)\s+:匹配前面有数字 (\d) 的任何空格 (\s)。

\s+(?=\d):匹配任何后跟数字的空格。

|:应用具有匹配项的连接表达式。

【讨论】:

  • 你能详细说明这个正则表达式吗?谢谢
【解决方案2】:

您可以通过类似数字的模式split,然后通过相同的模式findall。由于splitfindall 是“姐妹”函数,您将获得非数字和数字片段。现在,将它们压缩成一个列表并消除空格。

from itertools import chain
# You can improve the regex to cover numbers that start with a .
NUMBER = r'\d+(?:\.\d*)?'  
combined = chain.from_iterable(zip(re.split(NUMBER, a),                                                        
                                   re.findall(NUMBER, a)))
result = [x for x in map(str.strip, combined) if x]
#['IN', '744301', 'Mus Andaman & Nicobar Islands', '01', 'Nicobar',
# '638', 'Carnicobar', '9.2333', '92.7833', '4']

【讨论】:

    【解决方案3】:

    您可以将re.split 与一组(捕获括号)一起使用,以在结果中保留分隔符(数字):

    >>> import re
    >>> a = "IN 744301 Mus Andaman & Nicobar Islands   01  Nicobar 638 Carnicobar 9.2333  92.7833 4"
    >>> re.split(r'(\d+(?:\.\d+)?)', a)
    ['IN ', '744301', ' Mus Andaman & Nicobar Islands   ', '01', '  Nicobar ', '638', ' Carnicobar ', '9.2333', '  ', '92.7833', ' ', '4', '']
    

    【讨论】:

    • 你能详细说明这个正则表达式吗?谢谢
    • 在 regex101.com 上试试
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多