使用分隔符作为空白分割字符串,但它在doubleqoutes中保留空白,在Python中也保留doubleqoutes

2024-10-03 00:22:38 发布

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

分隔符为空白的拆分字符串,但它应该在doubleqoutes中保留空白,在Python中也应该保留doubleqoutes

a='Append ",","te st1",input To output'

输出列表如下

['Append', '",","te st1",input', 'To', 'output']

Tags: to字符串列表inputoutput空白分隔符te
2条回答

一个非常简单的生成器函数,保持当前的“引用状态”:

def splitter(s):
    i, quoted = 0, False
    for n, c in enumerate(s+' '):
        if c == '"':
            quoted = not quoted
        elif c == ' ' and not quoted:
            if n > i:
                yield s[i:n]
            i = n+1

list(splitter(a))
# ['Append', '",","te st1",input', 'To', 'output']

我找到了一个使用正则表达式的解决方案:

re.findall("(?:\".*?\"|\S)+", a)

给予

['Append', '",","te st1",input', 'To', 'output']

更新:改进的模式,包括转义:

re.findall("(?:\".*?[^\\\"]\"|\S)+", a)

请注意,这还通过模式的\S部分匹配空字符串""。你知道吗

注:出于存档目的,以下为旧答案:

显而易见的答案是这样使用shlex

>>> shlex.split('Append ",","te st1",input To output')
['Append', ',,te st1,input', 'To', 'output']

不幸的是,这将删除引号。总之,这种问题可以用一个简单的状态机来解决。性能可能低于标准,但它是有效的:

#!/usr/bin/env python2

import string

def split_string_whitespace(s):
    current_token = []
    result = []
    state = 0
    for c in s + " ":
        if state == 0:
            if c in string.whitespace:
                if current_token:
                    result.append("".join(current_token))
                    current_token = []
            else:
                current_token.append(c)
                if c == '"':
                    state = 1
        else:
            current_token.append(c)
            if c == '"':
                state = 0
    return result

print split_string_whitespace('Append ",","te st1",input To output')

脚本产生:

['Append', '",","te st1",input', 'To', 'output']

我很确定可以用re子模块构造一些东西,所以我也在等待答案:)

相关问题 更多 >