【发布时间】:2020-11-16 07:27:28
【问题描述】:
如果我需要编写一个函数来读取一个大段落并打印出段落中每个长度有多少个单词,我该怎么做?
这是我迄今为止尝试过的。
#split the piece of writing into a list so I can search over every word
#need to find out how to make this not take so long
piece = "hello world"
words = piece.split()
#search over every word, have a variable for each number, check to see length of word and add correspondingly
for word in range(words):
one = 0
two = 0
three = 0
four = 0
five = 0
six = 0
seven = 0
eight = 0
nine = 0
ten = 0
eleven = 0
twelve = 0
thirteen = 0
other = 0
total = 0
if (len(word) == 1):
one += 1
total += 1
elif (len(word) == 2):
two += 1
total += 1
elif (len(word) == 3):
three += 1
total += 1
elif (len(word) == 4):
four += 1
total += 1
elif (len(word) == 5):
five += 1
total += 1
elif (len(word) == 6):
six += 1
total += 1
elif (len(word) == 7):
seven += 1
total += 1
elif (len(word) == 8):
eight += 1
total += 1
elif (len(word) == 9):
nine += 1
total += 1
elif (len(word) == 10):
ten += 1
total += 1
elif (len(word) == 11):
eleven += 1
total += 1
elif (len(word) == 12):
twelve += 1
total += 1
elif (len(word) == 13):
thirteen += 1
total += 1
else:
other += 1
total += 1
#print results
print(f'Proportion of 1- letter words: {one / total * 100}% {one} words')
print(f'Proportion of 2- letter words: {two / total* 100}% {two} words')
print(f'Proportion of 3- letter words: {three / total* 100}% {three} words')
print(f'Proportion of 4- letter words: {four / total * 100}% {four} words')
print(f'Proportion of 5- letter words: {five / total * 100}% {five} words')
print(f'Proportion of 6- letter words: {six / total * 100}% {six} words')
print(f'Proportion of 7- letter words: {seven/ total * 100}% {seven} words')
print(f'Proportion of 8- letter words: {eight / total * 100}% {eight} words')
print(f'Proportion of 9- letter words: {nine / total * 100}% {nine} words')
print(f'Proportion of 10- letter words: {ten / total * 100}% {ten} words')
print(f'Proportion of 11- letter words: {eleven / total * 100}% {eleven} words')
print(f'Proportion of 12- letter words: {twelve / total * 100}% {twelve} words')
print(f'Proportion of 13- letter words: {thirteen / total * 100}% {thirteen} words')
我认为这两个问题是我不知道如何让循环在段落的整个长度内运行,而且我不知道如何编写代码,以便使用大量文本不需要永远运行。
【问题讨论】:
标签: python list counting word letter