解析器提供了一个用于指定注释字符的选项,但它在简化界面中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']