我想将字符串转换为单词列表,但我想将引号中的单词保留为字符串。这就是我正在寻找的东西:
>> 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]
我将如何继续解决这个问题?
例如:
>>> 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']