0

shlex如果找到了角色,如何判断;,那么,不要再分割任何东西了?

例子:

shlex.split("""hello "column number 2" foo ; bar baz""")  

应该给

["hello", "column number 2", "foo", "; bar baz"]

而不是["hello", "column number 2", "foo", ";", "bar", "baz"].


更一般地说,有没有办法用 ? 定义“评论”分隔符shlex?IE

shlex.split("""hello "column number 2" foo ;this is a comment; "last one" bye """)  

应该给

["hello", "column number 2", "foo", ";this is a comment;", "last one", "bye"]
4

1 回答 1

1

解析器提供了一个用于指定注释字符的选项,但它在简化界面中shlex不可用。shlex.split例子:

import shlex

a = 'hello "bla bla" ; this is a comment'

lex = shlex.shlex(a, posix=True)
lex.commenters = ';'
print(list(lex))  # ['hello', 'bla bla']

这是一个稍微扩展的split函数,大部分是从 Python 标准库中复制的,对参数稍作修改comments,允许指定注释字符:

import shlex
def shlex_split(s, comments='', posix=True):
    """Split the string *s* using shell-like syntax."""
    if s is None:
        import warnings
        warnings.warn("Passing None for 's' to shlex.split() is deprecated.",
                      DeprecationWarning, stacklevel=2)
    lex = shlex.shlex(s, posix=posix)
    lex.whitespace_split = True
    if isinstance(comments, str):
        lex.commenters = comments
    elif not comments:
        lex.commenters = ''
    return list(lex)

您可能希望更改comments上述代码中的默认值;正如所写,它具有与 相同的默认值shlex.split,即根本不识别评论。(shlex.shlex默认情况下创建的解析器对象#作为注释字符,如果你指定,这是你得到comments=True的。为了兼容性,我保留了这个行为。)

请注意,注释被忽略;它们根本不会出现在结果向量中。当解析器遇到注释字符时,它会停止解析。(所以永远不可能有两条评论。)该comments字符串是可能的评论字符列表,而不是评论序列。因此,如果您想同时识别#; 作为注释字符,请指定comments='#:'.

这是一个示例运行:

>>> # Default behaviour is the same as shlex.split
>>> shlex_split("""hello "column number 2" foo ; bar baz""") 
['hello', 'column number 2', 'foo', ';', 'bar', 'baz']
>>> # Supply a comments parameter to specify a comment character 
>>> shlex_split("""hello "column number 2" foo ; bar baz""", comments=';') 
['hello', 'column number 2', 'foo']
>>> shlex_split("""hello "column number 2" foo ;this is a comment; "last one" bye """, comments=';')
['hello', 'column number 2', 'foo']
>>> # The ; is recognised as a comment even if it is not preceded by whitespace.
>>> shlex_split("""hello "column number 2" foo;this is a comment; "last one" bye """, comments=';')
['hello', 'column number 2', 'foo']
于 2021-01-14T21:44:55.050 回答