【问题标题】:Extract string from between quotations从引号之间提取字符串
【发布时间】:2011-01-05 18:55:57
【问题描述】:

我想从用户输入的文本中提取信息。想象一下,我输入以下内容:

SetVariables "a" "b" "c"

如何在第一组引用之间提取信息?那么第二个呢?那么第三个呢?

【问题讨论】:

    标签: python string extraction quotations


    【解决方案1】:
    >>> import re
    >>> re.findall('"([^"]*)"', 'SetVariables "a" "b" "c" ')
    ['a', 'b', 'c']
    

    【讨论】:

    • 行尾需要分号吗?
    【解决方案2】:

    Regular expressions 擅长这个:

    import re
    quoted = re.compile('"[^"]*"')
    for value in quoted.findall(userInputtedText):
        print value
    

    【讨论】:

      【解决方案3】:

      你可以对它做一个 string.split() 。如果字符串使用引号正确格式化(即偶数个引号),则列表中的每个奇数都将包含引号之间的元素。

      >>> s = 'SetVariables "a" "b" "c"';
      >>> l = s.split('"')[1::2]; # the [1::2] is a slicing which extracts odd values
      >>> print l;
      ['a', 'b', 'c']
      >>> print l[2]; # to show you how to extract individual items from output
      c
      

      这也是比正则表达式更快的方法。使用 timeit 模块,这段代码的速度大约快了 4 倍:

      % python timeit.py -s 'import re' 're.findall("\"([^\"]*)\"", "SetVariables \"a\" \"b\" \"c\" ")'
      1000000 loops, best of 3: 2.37 usec per loop
      
      % python timeit.py '"SetVariables \"a\" \"b\" \"c\"".split("\"")[1::2];'
      1000000 loops, best of 3: 0.569 usec per loop
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-05
        • 2020-03-18
        • 1970-01-01
        • 2020-01-26
        • 1970-01-01
        相关资源
        最近更新 更多