Extracting words from a string, removing punctuation and returning a list with separated words

后端 未结 3 1122
小蘑菇
小蘑菇 2020-12-03 07:50

I was wondering how to implement a function get_words() that returns the words in a string in a list, stripping away the punctuation.

How I would like t

3条回答
  •  忘掉有多难
    2020-12-03 08:22

    Try to use re:

    >>> [w for w in re.split('\W', 'Hello world, my name is...James!') if w]
    ['Hello', 'world', 'my', 'name', 'is', 'James']
    

    Although I'm not sure that it will catch all your use cases.

    If you want to solve it in another way, you may specify characters that you want to be in result:

    >>> re.findall('[%s]+' % string.ascii_letters, 'Hello world, my name is...James!')
    ['Hello', 'world', 'my', 'name', 'is', 'James']
    

提交回复
热议问题