防止 shlex 与冒号分裂 (:).



我在处理冒号(:)shlex(时遇到问题。我需要以下行为:

示例输入

text = 'hello:world ("my name is Max")'
s = shlex.shlex(instream=text, punctuation_chars=True)
s.get_token()
s.get_token()
...

期望的输出

hello:world
(
"my name is Max"
)

电流输出

hello
:
world
(
"my name is Max"
)

Shlex 将冒号放在一个单独的令牌中,我不希望这样。文档没有说太多关于冒号的信息。我试图将其添加到 wordchar 属性中,但它搞砸了一切并在逗号之间分隔单词。我还尝试将 punctuation_char 属性设置为仅带有括号的自定义数组:["(", "("],但这没有区别。我需要设置punctuation_char选项来将括号作为单独的令牌(或实现此输出的任何其他选项(获取。

有人知道我怎样才能让它工作吗?任何帮助将不胜感激。 我正在使用python 3.6.9,如有必要,可以升级到python 3.7.X。

要使shlex:视为单词字符,您需要在wordchars中添加:

>>> text = 'hello:world ("my name is Max")'
>>> s = shlex.shlex(instream=text, punctuation_chars=True)
>>> s.wordchars += ':'
>>> while True:
...   tok = s.get_token()
...   if not tok: break
...   print(tok)
... 
hello:world
(
"my name is Max"
)

我用Python 3.6.9和3.8.0测试了它。我认为您需要 Python 3.6 才能拥有punctuation_chars初始化参数。

最新更新