나는 문장 부호를 무시하고 텍스트를 단어로 분리하는 파이썬 함수를 작성하고있다. 여기에 몇 가지 작업 코드가 있습니다. 나는 목록에서 문자열을 생성하는 것이 효율적이라고 확신하지는 못한다. (코드에서 buf = [])는 효율적이다. 누구든지이 작업을 수행하는 더 좋은 방법에 대한 제안을 갖고 있습니까?반복적으로 파이썬에서 문자열에 추가하는 효과적인 방법은 무엇입니까?
def getwords(text, splitchars=' \t|!?.;:"'):
"""
Generator to get words in text by splitting text along specified splitchars
and stripping out the splitchars::
>>> list(getwords('this is some text.'))
['this', 'is', 'some', 'text']
>>> list(getwords('and/or'))
['and', 'or']
>>> list(getwords('one||two'))
['one', 'two']
>>> list(getwords(u'hola unicode!'))
[u'hola', u'unicode']
"""
splitchars = set(splitchars)
buf = []
for char in text:
if char not in splitchars:
buf.append(char)
else:
if buf:
yield ''.join(buf)
buf = []
# All done. Yield last word.
if buf:
yield ''.join(buf)
너무 나쁨 ... 여기에 누가 가장 좋은 답변을 넣었는지, 내장 된 분할로 둘 이상의 머리말을 붙일 수 있다고 말했습니다. 당신은 그의 코드가 추악하다고 말했고, 그는 그의 메시지를 삭제했습니다. – fulmicoton