我想从用户输入的文本中提取信息。假设我输入了以下内容:
SetVariables "a" "b" "c"
如何提取第一组报价之间的信息?那第二个呢?那第三个呢?
发布于 2010-01-16 13:58:24
>>> import re
>>> re.findall('"([^"]*)"', 'SetVariables "a" "b" "c" ')
['a', 'b', 'c']
发布于 2010-01-16 14:16:45
您可以对其执行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
发布于 2010-01-16 13:58:29
Regular expressions擅长这一点:
import re
quoted = re.compile('"[^"]*"')
for value in quoted.findall(userInputtedText):
print value
https://stackoverflow.com/questions/2076343
复制相似问题