【问题标题】:Split string with multiple separators from an array (Python)从数组中拆分具有多个分隔符的字符串(Python)
【发布时间】:2018-01-10 00:46:25
【问题描述】:

给定一个分隔符数组:

columns = ["Name:", "ID:", "Date:", "Building:", "Room:", "Notes:"]

还有一个字符串,其中一些列留空(并且有随机空格):

input = "Name:      JohnID:123:45Date:  8/2/17Building:Room:Notes:  i love notes"

我怎样才能得到这个:

["John", "123:45", "8/2/17", "", "", "i love notes"]

我尝试简单地删除子字符串以查看我可以从那里去哪里,但我仍然卡住了

import re
input = re.sub(r'|'.join(map(re.escape, columns)), "", input)

【问题讨论】:

    标签: python split delimiter


    【解决方案1】:

    使用列表通过在其间插入(.*) 来生成正则表达式,然后使用strip 删除空格:

    import re
    
    columns = ["Name:", "ID:", "Date:", "Building:", "Room:", "Notes:"]
    s = "Name:      JohnID:123:45Date:  8/2/17Building:Room:Notes:  i love notes"
    
    result = [x.strip() for x in re.match("".join(map("{}(.*)".format,columns)),s).groups()]
    
    print(result)
    

    产量:

    ['John', '123:45', '8/2/17', '', '', 'i love notes']
    

    strip 部分可以由正则表达式处理,但代价是更复杂的正则表达式,但整体表达式更简单:

    result = re.match("".join(map("{}\s*(.*)\s*".format,columns)),s).groups()
    

    更复杂:如果字段数据包含正则表达式特殊字符,我们必须转义它们(这里不是这种情况):

    result = re.match("".join(["{}\s*(.*)\s*".format(re.escape(x)) for x in columns]),s).groups()
    

    【讨论】:

    • 由于某种原因,我收到了['John', '123:45', '8/2/17', '', '', '']
    • 已编辑,贪心模式明显导致问题。现已修复。
    【解决方案2】:

    re.split怎么样?

    >>> import re
    >>> columns = ["Name:", "ID:", "Date:", "Building:", "Room:", "Notes:"]
    >>> i = "Name:      JohnID:123:45Date:  8/2/17Building:Room:Notes:  i love notes"
    >>> re.split('|'.join(map(re.escape, columns)), i)
    ['', '      John', '123:45', '  8/2/17', '', '', '  i love notes']
    

    要摆脱空白,也可以拆分空白:

    >>> re.split(r'\s*' + (r'\s*|\s*'.join(map(re.escape, columns))) + r'\s*', i.strip())
    ['', 'John', '123:45', '8/2/17', '', '', '  i love notes']
    

    【讨论】:

    • 很好,可能是 OP 的想法。但在开始时发出一个空字段。
    • @Jean-FrançoisFabre 开头的空白字段是因为您按值 "Name:" 拆分。左边什么都没有,所以它是一个空字符串。左边可能有东西。
    猜你喜欢
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多