从引号中提取字符串

41 投票
3 回答
104836 浏览
提问于 2025-04-15 18:05

我想从用户输入的文本中提取信息。假设我输入了以下内容:

SetVariables "a" "b" "c"

我该如何提取第一个引号之间的信息?然后是第二个?再然后是第三个?

3 个回答

17

正则表达式在这方面非常有效:

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

你可以对这个字符串使用 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
67
>>> import re
>>> re.findall('"([^"]*)"', 'SetVariables "a" "b" "c" ')
['a', 'b', 'c']

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

撰写回答