Мне нужна помощь, чтобы код разбил предложение.где бы я ввести функцию разделения в моем коде - PullRequest
0 голосов
/ 04 мая 2019

В настоящее время мой код работает для списков, но не для предложений.Мне нужна помощь с превращением предложения в список.где бы я мог ввести функцию .split в мой код?

def stats(word_list):
    'prints number, longest and average length of word_list'
    length = len(word_list)
    print("The number of words is {}.".format(length))
    char_count = 0
    longest_so_far = ""
    for word in word_list:
        # char_count = char_count + len(word)
        char_count += len(word)
        if len(word) > len(longest_so_far):
            longest_so_far = word

    print("The longest word is " + longest_so_far + ".")
    average = char_count / length
    message = "The average length is {}.".format(average)
    print(message)

1 Ответ

1 голос
/ 04 мая 2019

Это можно сделать в первой строке функции, когда вы передаете строку и делаете string.split, чтобы получить word_list

def stats(sentence):
    'prints number, longest and average length of word_list'

    #Split sentence to a list of words here
    word_list = sentence.split()

    length = len(word_list)
    print("The number of words is {}.".format(length))
    char_count = 0
    longest_so_far = ""
    for word in word_list:
        # char_count = char_count + len(word)
        char_count += len(word)
        if len(word) > len(longest_so_far):
            longest_so_far = word

    print("The longest word is " + longest_so_far + ".")
    average = char_count / length
    message = "The average length is {}.".format(average)
    print(message)

stats('i am a sentence')

Выход будет

The number of words is 4.
The longest word is sentence.
The average length is 3.0.

Вы также можете оптимизировать свой код следующим образом

def stats(sentence):
    'prints number, longest and average length of word_list'

    #Split sentence here in word here
    word_list = sentence.split()
    length = len(word_list)

    print("The number of words is {}.".format(length))

    #Sort the word list on word length in reverse order
    sorted_word_list = sorted(word_list, key=len, reverse=True)

    #The longest element will be first element in that list
    print("The longest word is " + sorted_word_list[0] + ".")

    #Calcuate length of each word and sum all lengths together
    char_count = sum([len(w) for w in word_list])

    #Calculate average and print it
    average = char_count / length
    message = "The average length is {}.".format(average)
    print(message)

stats('i am a sentence')
...