【问题标题】:Python shlex.split(), ignore single quotesPython shlex.split(),忽略单引号
【发布时间】:2011-10-15 15:39:16
【问题描述】:

如何在 Python 中使用 shlex.split() 或类似的方法来拆分字符串,只保留双引号?例如,如果输入为"hello, world" is what 'i say',则输出为["hello, world", "is", "what", "'i", "say'"]

【问题讨论】:

  • 捕获整个双引号字符串,但拆分单引号字符串。
  • +1 有趣的问题。这些天我很少写 Python,而且我以前从未见过或使用过shlex,所以这是一个有趣的。
  • 这些天Python真的是我的工作描述

标签: python split quotes shlex


【解决方案1】:
import shlex

def newSplit(value):
    lex = shlex.shlex(value)
    lex.quotes = '"'
    lex.whitespace_split = True
    lex.commenters = ''
    return list(lex)

print newSplit('''This string has "some double quotes" and 'some single quotes'.''')

【讨论】:

  • 只能忽略不计,lex.commenters 位实际上是我的回答没有做的事情。 +1 获取 git-r-dun 的不同方式。
  • 我从 python 源中的 shlex.split 函数的源代码开始,然后用引号字符列表对其进行了调整。
  • 我花了一段时间,但这与通过 posix 的普通 shlex.split 略有不同...shlex.shlex(value, posix=True)
【解决方案2】:

您可以使用shlex.quotes 来控制哪些字符将被视为字符串引号。您还需要修改 shlex.wordchars,以保留 'isay

import shlex

input = '"hello, world" is what \'i say\''
lexer = shlex.shlex(input)
lexer.quotes = '"'
lexer.wordchars += '\''

output = list(lexer)
# ['"hello, world"', 'is', 'what', "'i", "say'"]

【讨论】:

  • 实际上,这个在我写的其他东西上失败了,而彼得的工作。不过谢谢!
  • 出于好奇,它在什么输入上失败了?
  • 如果转义的引用在引用的部分,有没有前进的方向?说,s = "1 'K\^o, Suzuk\'e'" 拆分成[1, "K\^o, Suzuk\'e"]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-11
  • 1970-01-01
  • 2012-08-12
  • 2017-04-22
  • 1970-01-01
  • 2014-02-26
相关资源
最近更新 更多