在Python中使用空格作为分隔符拆分字符串,除非空格在引号之间

3
我想通过空格分割文本,除非空格在引号之间才算分隔符。
例如:
string = "my name is 'solid snake'"
output = ["my","name","is","'solid snake'"]

请查看以下网址:https://dev59.com/SXRC5IYBdhLWcg3wP-dh - Chris Lear
1
@ChrisLear 这被标记为Java,我不认为它能与Python的正则表达式风格一起使用。 - Umar.H
1
不需要烦恼正则表达式,使用import shlex; shlex.split(text, posix=False)即可。请参见答案 - Wiktor Stribiżew
2
@WiktorStribiżew,尽管我已经回答了,但我同意那个链接。我对那个模块一无所知!它非常好用。 - JvdV
2个回答

2
循环字符串:
string = "my name is 'solid snake'"
quotes_opened = False
out = []
toadd = ''
for c, char in enumerate(string):
    if c == len(string) - 1: #is the character the last char
        toadd += char
        out.append(toadd); break
    elif char in ("'", '"'): #is the character a quote
        if quotes_opened:
            quotes_opened = False #if quotes are open then close
        else:
            quotes_opened = True #if quotes are closed the open
        toadd += char
    elif char != ' ':
        toadd += char #add the character if it is not a space
    elif char == ' ': #if character is a space
        if not quotes_opened: #if quotes are not open then add the string to list
            out.append(toadd)
            toadd = ''
        else: #if quotes are still open then do not add to list
            toadd += char
print(out)

1
一种蛮力的方法是:
string = "my name is 'solid snake'"
output = ["my","name","is","'solid snake'"]

ui= "__unique__"

string2= string.split("'")
print(string2)

for i, segment in enumerate(string2):
    if i %2 ==1:
        string2[i]=string2[i].replace(" ",ui)
        
print(string2)

string3= "'".join(string2)

print(string3)

string4=string3.split(" ")

print(string4)

for i, segment in enumerate(string4):
    if ui in segment:
        string4[i]=string4[i].replace("__unique__", " ")

print()
print(string4)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接