0

我在处理 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。

4

1 回答 1

0

要将其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初始化参数。

于 2020-05-11T19:39:04.260 回答