【问题标题】:I need help making the code split the sentence. where would I input the split function in my code我需要帮助使代码拆分句子。我将在我的代码中在哪里输入拆分函数
【发布时间】:2019-05-04 12:25:33
【问题描述】:

目前我的代码适用于列表,但不适用于句子。我需要帮助将句子变成列表。我应该在哪里将 .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)

【问题讨论】:

  • 考虑接受对你有用的答案。
  • 如果我的回答对你有用!请考虑接受它@riser1234 :)

标签: python function split python-3.7


【解决方案1】:

您可以在函数的第一行执行此操作,当您传递一个字符串并执行 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')

【讨论】:

  • 很高兴帮助@riser1234!如果回答对你有帮助!请考虑通过单击答案旁边的勾号来接受它:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-21
  • 2012-08-03
  • 1970-01-01
  • 2018-02-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多