2014-11-22 14 views
1

특정 문자가 나타날 때 문자열을 분할하려고합니다. (예 :!,! etc) split 함수를 작성했지만 분할하지만 그 문자는 제거됩니다. 내가 예를 들어 함수를 호출 할 때 :char에서 split하지만 char - python을 그대로 두십시오.

text = 'The first line leads off, With a gap before the next. Then the poem ends.' 

를 내가 얻을

문자가 제거되지 않습니다 때문에 변경할 필요가 무엇
['The first line leads off', ' With a gap before the next', ' Then the poem ends'] 

그래서 난이 얻을 것이다 :

['The first line leads off,', ' With a gap before the next.', ' Then the poem ends.'] 

을 .

def split_on_separators(original, separators): 


    word_list = [original] 
    new_list = [ ] 
    for given in separators: 
     for word in word_list:     
      new_list.extend(word.split(given)) 

     word_list = new_list      
     new_list = list()      
    return word_list 

감사합니다.

+0

나의 제안이에 대한 자신의 함수를 작성하지 않는 것, 당신이 그것을 달성하기 위해 파이썬 내에서 사용할 수있는 많은 자원이있다. 자세한 내용은 내 대답을 참조하십시오. 그건 그렇고, 당신 Stackoverflow에 대한 답변을 받아 들일 수 있고 더 나은 것들을 받아 들일 수있다;) – mdadm

답변

0
def splitOnChars(text, chars): 
    answer = [] 
    start = 0 
    for i,char in enumerate(text): 
     if char in chars: 
      answer.append(text[start:i+1]) 
      start = i+1 
    answer.append(text[i+1:]) 
    return answer 

출력 :

In [41]: text = 'The first line leads off, With a gap before the next. Then the poem ends.' 

In [42]: chars = ',.!' 

In [43]: splitOnChars(text, chars) 
Out[43]: 
['The first line leads off,', 
' With a gap before the next.', 
' Then the poem ends.', 
''] 
+0

다른 제출보다 훨씬 깔끔하고, 아마도 zip이나 re.split없이 그것을 할 수있는 가장 좋은 방법 일 것이다. 나는이 IMHO를 해결할 더 파이썬적인 방법이 있다고 생각한다. – mdadm

+0

왜 downvote? – inspectorG4dget

1

또는이에 대한 자신의 함수를 작성 잊고 re.split 및 우편을 사용할 수 있습니다. re.split은 캡처 그룹을 사용할 때 결과 목록에 구분 기호를 다음 요소로 남겨 둡니다. 두 개의 다른 단계 반복 및 압축을 사용하여 다시 결합 할 수 있습니다.

import re 
mypoem = 'The first line leads off, With a gap before the next. Then the poem ends.' 

junk = re.split("(,|\.)", mypoem) 
poem_split = [i1 + i2 for i1, i2 in zip(junk[0::2], junk[1::2])] 
0

그냥 정규 표현식을 사용

import re 

text = 'The first line leads off, With a gap before the next. Then the poem ends.' 
print re.findall('.*?[,.!]?', text) 
# ['The first line leads off,', ' With a gap before the next.', ' Then the poem ends.'] 
관련 문제