Split Strings into words with multiple word boundary delimiters

前端 未结 30 2692
既然无缘
既然无缘 2020-11-21 05:09

I think what I want to do is a fairly common task but I\'ve found no reference on the web. I have text with punctuation, and I want a list of the words.

\"H         


        
30条回答
  •  悲哀的现实
    2020-11-21 06:03

    I like the replace() way the best. The following procedure changes all separators defined in a string splitlist to the first separator in splitlist and then splits the text on that one separator. It also accounts for if splitlist happens to be an empty string. It returns a list of words, with no empty strings in it.

    def split_string(text, splitlist):
        for sep in splitlist:
            text = text.replace(sep, splitlist[0])
        return filter(None, text.split(splitlist[0])) if splitlist else [text]
    

提交回复
热议问题