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']
#!/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')
一个非常简单的生成器函数,保持当前的“引用状态”:
我找到了一个使用正则表达式的解决方案:
给予
更新:改进的模式,包括转义:
请注意,这还通过模式的
\S
部分匹配空字符串""
。你知道吗注:出于存档目的,以下为旧答案:
显而易见的答案是这样使用
shlex
:不幸的是,这将删除引号。总之,这种问题可以用一个简单的状态机来解决。性能可能低于标准,但它是有效的:
脚本产生:
我很确定可以用
re
子模块构造一些东西,所以我也在等待答案:)相关问题 更多 >
编程相关推荐