Проблема: разделите строку на список слов разделителями символов, переданных в виде списка.string split issue
Строка: "After the flood ... all the colors came out."
Желаемый результат: ['After', 'the', 'flood', 'all', 'the', 'colors', 'came', 'out']
Я написал следующую функцию - обратите внимание, я знаю, что есть лучшие способы разбить строку, используя некоторые из питонов встроенных функций, но ради обучения я думал, что будет продолжаться так:
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', '', '', '', '', '', '', '', '', '']
Я не могу понять, почему «вышел» не разделяется на «пришел» и «из», как два отдельных слова. Его как будто пробельный символ между двумя словами игнорируется. Я думаю, что остальная часть вывода - это хлам, который связан с проблемой, связанной с проблемой «вышла».
EDIT:
Я последовал @ предложение 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']
Благодарим вас за прекрасные решения. Я пошел с этим, потому что он заставляет меня изучать логику вместо использования предварительно построенных функций. Очевидно, что если бы я написал коммерческий код, я бы не изобрел колесо, но для учебных целей я пойду с этим ответом. Спасибо за вашу помощь. – codingknob