如果我遍历字符串中的所有字符,我知道如何做到这一点,但我正在寻找一个更优雅的方法.
我想解析这样的字符串:
-o 1 --long "Some long string"
Run Code Online (Sandbox Code Playgroud)
进入这个:
["-o", "1", "--long", 'Some long string']
Run Code Online (Sandbox Code Playgroud)
或类似的.
这与getopt或optparse不同,后者以sys.argv解析的输入开头(就像我上面的输出一样).有没有标准的方法来做到这一点?基本上,这是"分裂",同时保持引用的字符串在一起.
到目前为止我的最佳功能:
import csv
def split_quote(string,quotechar='"'):
'''
>>> split_quote('--blah "Some argument" here')
['--blah', 'Some argument', 'here']
>>> split_quote("--blah 'Some argument' here", quotechar="'")
['--blah', 'Some argument', 'here']
'''
s = csv.StringIO(string)
C = csv.reader(s, delimiter=" ",quotechar=quotechar)
return list(C)[0]
Run Code Online (Sandbox Code Playgroud) 给出这样的字符串:
a,"字符串,带",各种各样的,"价值观和一些",引用
在忽略引用部分中的逗号的同时,基于逗号分割它的好算法是什么?
输出应该是一个数组:
["a","string,with","various","values,and some","quoted"]