Python: Finding The Longest/Shortest Sentence In A Random Paragraph?

前端 未结 3 682
感情败类
感情败类 2021-01-27 02:51

I am using Python 2.7 and need 2 functions to find the longest and shortest sentence (in terms of word count) in a random paragraph. For exampl

3条回答
  •  鱼传尺愫
    2021-01-27 03:35

    You need a way to split the paragraph into sentences and to count words in a sentence. You could use nltk package for both:

    from nltk.tokenize import sent_tokenize, word_tokenize # $ pip install nltk
    
    sentences = sent_tokenize(paragraph)
    word_count = lambda sentence: len(word_tokenize(sentence))
    print(min(sentences, key=word_count)) # the shortest sentence by word count
    print(max(sentences, key=word_count)) # the longest sentence by word count
    

提交回复
热议问题