2010-01-16 110 views
18

我想從用戶輸入的文本中提取信息。想象一下,我輸入以下內容:從引號之間提取字符串

SetVariables "a" "b" "c" 

我將如何提取第一組報價之間的信息?那第二個?那麼第三個?

回答

26
>>> import re 
>>> re.findall('"([^"]*)"', 'SetVariables "a" "b" "c" ') 
['a', 'b', 'c'] 
+0

是否需要在行尾加上分號? – User 2014-03-14 18:16:56

+0

@jspcal這是否也適用於單引號? – 2015-05-21 22:28:08

9

Regular expressions這是好的:

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

你可以在上面做一個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