我想从用户输入的文本中提取信息。假设我输入以下内容:
SetVariables "a" "b" "c"
我该如何提取第一组引号之间的信息?然后是第二组?第三组呢?
我想从用户输入的文本中提取信息。假设我输入以下内容:
SetVariables "a" "b" "c"
我该如何提取第一组引号之间的信息?然后是第二组?第三组呢?
>>> import re
>>> re.findall('"([^"]*)"', 'SetVariables "a" "b" "c" ')
['a', 'b', 'c']
>>> 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
正则表达式 可以很好地完成这个任务:
import re
quoted = re.compile('"[^"]*"')
for value in quoted.findall(userInputtedText):
print value
;
)允许您在一行上放置两个命令,但这种做法在大多数情况下是不鼓励的。 - WinEunuuchs2Unix