【问题标题】:parsing a string based on specified identifiers根据指定的标识符解析字符串
【发布时间】:2010-05-11 22:44:02
【问题描述】:

假设我有以下文本:

input = "one aaa and bbb two bbbb er ... // three cccc"

我想将其解析为一组包含

的变量
criteria = ["one", "two", "three"]
v1,v2,v3 = input.split(criteria)

我知道上面的例子行不通,但是 python 中是否有一些实用程序可以让我使用这种方法?我事先知道标识符是什么,所以我认为必须有办法做到这一点......

感谢您的帮助, jml

【问题讨论】:

    标签: python string parsing


    【解决方案1】:

    不是很优雅,但很有效:

    >>> s
    'one aaa two bbbb three cccc'
    >>> re.split(r"\s*(?:one|two|three)\s*", s)
    ['', 'aaa', 'bbbb', 'cccc']
    

    ?: 阻止它返回结果中的定界标识符。

    【讨论】:

      【解决方案2】:

      所以,太丑了,但它应该做你需要的:

      i1 = iter(input.split())
      i2 = iter(input.split())
      next(i2)
      strdict = dict(zip(i1, i2))
      print operator.itemgetter(*criteria)(strdict)
      

      【讨论】:

      • 非常酷。我不认为它是丑!我的意思是;考虑这是在 c 中完成的。 :)
      猜你喜欢
      • 1970-01-01
      • 2021-03-19
      • 2015-09-09
      • 2014-06-21
      • 2013-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-29
      相关资源
      最近更新 更多