我很难处理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。
发布于 2020-05-11 19:39:04
要使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"
)我用Python3.6.9和3.8.0进行了测试。我认为您需要Python3.6才能获得punctuation_chars初始化参数。
https://stackoverflow.com/questions/61735871
复制相似问题