我想通过空格分割文本,除非空格在引号之间才算分隔符。
例如:
例如:
string = "my name is 'solid snake'"
output = ["my","name","is","'solid snake'"]
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)
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)
import shlex; shlex.split(text, posix=False)
即可。请参见答案。 - Wiktor Stribiżew