将字符串转换为单词列表,但将单词加引号在一起

问题描述 投票:0回答:1

我想将字符串转换为单词列表,但我想将引号中的单词保留为字符串。这就是我正在寻找的东西:

>> foo = 'some words "other words in quotes"'
>> bar = convert(foo)
>> bar 
['some','words','other words in quotes']

[在我的research中,我发现人们使用split(),切片和正则表达式,但没有比这更多的东西了:

def convert(string):
    InQuotes = string.split('"')[1::2]

我将如何继续解决这个问题?

regex python-3.x string list slice
1个回答
0
投票

例如:

>>> import re
>>> re.findall(r'\w+|"[^"]*"', foo)
['some', 'words', '"other words in quotes"']

然后,您需要进行其他清理以删除引号。您也可以这样做:

>>> list(map(''.join, re.findall(r'(\w+)|"([^"]*)"', foo)))
['some', 'words', 'other words in quotes']
© www.soinside.com 2019 - 2024. All rights reserved.