Как предотвратить, что процедура, аналогичная функции split () (но с несколькими разделителями), возвращает '' в свой вывод - PullRequest
0 голосов
/ 17 марта 2012

ребята, я новичок в программировании, пытающийся улучшить процедуру ниже таким образом, чтобы при передаче аргумента: split_string("After the flood ... all the colors came out."," .") он возвращал:

['After', 'the', 'flood', 'all', 'the', 'colors', 'came', 'out']

, а не это:

['After', 'the', 'flood', '', '', '', '', 'all', 'the', 'colors', 'came', 'out', ''] 

Есть подсказка, как это сделать?(Я мог бы просто повторить список и удалить элементы '', но я хотел более элегантное решение)

Это процедура:

def split_string(source, separatorList):
    splited = [source]
    for separator in splitlist:
        source = splited
        splited = []
        print 'separator= ', separator
        for sequence in source:
            print 'sequence = ', sequence
            if sequence not in splitlist and sequence != ' ':
                splited = splited + sequence.split(separator)            
    return splited

print split_string("This is a test-of the,string separation-code!", " ,!-")
print
print split_string("After  the flood   ...  all the colors came out."," .")

Ответы [ 3 ]

3 голосов
/ 17 марта 2012
print re.split('[. ]+', 'After the flood ... all the colors came out.')

или, лучше, наоборот

print re.findall('[^. ]+', 'After the flood ... all the colors came out.')
3 голосов
/ 17 марта 2012

Вы можете отфильтровать пустые строки в операторе возврата:

return [x for x in split if x]

В качестве примечания, я думаю, что было бы проще написать вашу функцию на основе re.split():

def split_string(s, separators):
    pattern = "|".join(re.escape(sep) for sep in separators)
    return [x for x in re.split(pattern, s) if x]
1 голос
/ 18 марта 2012

Давайте посмотрим, откуда появились пустые строки, попробуйте выполнить это в оболочке:

>>> 'After the'.split(' ')

result:

['After', '', 'the']

Это произошло потому, что когда метод split пришел к ' ' в строке, он не находит ничего, кроме '' между двумя пробелами.

Итак, решение простое, просто проверьте логическое значение каждого элементаот .split(

def split_string(source, separatorList):
    splited = [source]
    for separator in separatorList:
        # if you want to exchange two variables, then write in one line can make the code more clear
        source, splited = splited, []
        for sequence in source:
            # there's no need to check `sequence` in advance, just split it
            # if sequence not in separatorList and sequence != ' ':
                # splited = splited + sequence.split(separator)

            # code to prevent appearance of `''` is here, do a if check in list comprehension.
            # `+=` is equivalent to `= splited +`
            splited += [i for i in sequence.split(separator) if i]
    return splited

Подробнее о [i for i in a_list if i] см. PEP 202

...