【问题标题】:Prevent shlex from splitting with colon (:)防止 shlex 用冒号 (:) 拆分
【发布时间】:2020-05-11 17:43:24
【问题描述】:

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

【问题讨论】:

    标签: python-3.x parsing shlex


    【解决方案1】:

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

    【讨论】:

    • 好吧,这行得通!非常感谢。我之前肯定在 wordchars 属性上做错了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-13
    相关资源
    最近更新 更多