How to split a string into a list?

后端 未结 9 2467
执念已碎
执念已碎 2020-11-21 04:32

I want my Python function to split a sentence (input) and store each word in a list. My current code splits the sentence, but does not store the words as a list. How do I do

9条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 05:20

    Depending on what you plan to do with your sentence-as-a-list, you may want to look at the Natural Language Took Kit. It deals heavily with text processing and evaluation. You can also use it to solve your problem:

    import nltk
    words = nltk.word_tokenize(raw_sentence)
    

    This has the added benefit of splitting out punctuation.

    Example:

    >>> import nltk
    >>> s = "The fox's foot grazed the sleeping dog, waking it."
    >>> words = nltk.word_tokenize(s)
    >>> words
    ['The', 'fox', "'s", 'foot', 'grazed', 'the', 'sleeping', 'dog', ',', 
    'waking', 'it', '.']
    

    This allows you to filter out any punctuation you don't want and use only words.

    Please note that the other solutions using string.split() are better if you don't plan on doing any complex manipulation of the sentence.

    [Edited]

提交回复
热议问题