Задача: разбить строку на список слов с помощью символов-разделителей, переданных в виде списка.
Строка: "После потопа... вышли все цвета".
Желаемый результат: ['После', 'то', 'наводнение', 'все', 'то', 'цвета', 'пришел', 'вышло']
Я написал следующее функция — примечание. Я знаю, что есть лучшие способы разбить строку, используя некоторые встроенные функции питонов, но ради обучения я подумал, что буду действовать следующим образом:
def split_string(source,splitlist):
result = []
for e in source:
if e in splitlist:
end = source.find(e)
result.append(source[0:end])
tmp = source[end+1:]
for f in tmp:
if f not in splitlist:
start = tmp.find(f)
break
source = tmp[start:]
return result
out = split_string("After the flood ... all the colors came out.", " .")
print out
['After', 'the', 'flood', 'all', 'the', 'colors', 'came out', '', '', '', '', '', '', '', '', '']
Я не могу понять, почему «вышел» не делится на «пришел» и «вышел» как два отдельных слова. Как будто пробел между двумя словами игнорируется. Я думаю, что остальная часть вывода - это мусор, связанный с проблемой, связанной с проблемой «вышел».
РЕДАКТИРОВАТЬ:
Я последовал предложению @Ivc и придумал следующий код:
def split_string(source,splitlist):
result = []
lasti = -1
for i, e in enumerate(source):
if e in splitlist:
tmp = source[lasti+1:i]
if tmp not in splitlist:
result.append(tmp)
lasti = i
if e not in splitlist and i == len(source) - 1:
tmp = source[lasti+1:i+1]
result.append(tmp)
return result
out = split_string("This is a test-of the,string separation-code!"," ,!-")
print out
#>>> ['This', 'is', 'a', 'test', 'of', 'the', 'string', 'separation', 'code']
out = split_string("After the flood ... all the colors came out.", " .")
print out
#>>> ['After', 'the', 'flood', 'all', 'the', 'colors', 'came', 'out']
out = split_string("First Name,Last Name,Street Address,City,State,Zip Code",",")
print out
#>>>['First Name', 'Last Name', 'Street Address', 'City', 'State', 'Zip Code']
out = split_string(" After the flood ... all the colors came out...............", " ."
print out
#>>>['After', 'the', 'flood', 'all', 'the', 'colors', 'came', 'out']