目前,我的代码适用于列表,但不适用于句子。我需要将句子变成列表的帮助。我应该在哪里在代码中输入.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)
答案 0 :(得分: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')