计算字符串中每个单词的字母
Counting the letters of each word in a string
在尝试完成我的一门大学课程时,我遇到了其中一项练习,该练习计算我必须收到的文本中每个单词的字母,直到所有字母的总和 >= 1000,但它永远不会即使文本超过 1000,也会达到 1000。
首先,我认为这可能是因为我没有收到完整的消息,但在查看并弄乱了我创建的不同功能后(none 其中解决了这个问题)它似乎是我的柜台功能不工作。 (这个计数器函数 returns 一个数字数组,稍后我将其转换为字符串)
有什么我没弄明白的东西弄乱了我的代码吗?
def letterCounter(text):
counter = 0
indice = 0
lettTotal = 0
totalCount = []
while True:
if text[indice] == " ":
totalCount.append(counter)
counter = 0
indice += 1
else:
counter += 1
lettTotal += 1
indice += 1
if lettTotal >= 1000:
break
return totalCount
编辑:
-样本
输入:
authority stuff Design reach speak professor worker Executive future factor police spring live seek specific Easy What lot continue chair area military may matter Mention act bed Government all positive reflect Product plan Check Painting drop bar general weight anything to policy Control series over gas blue trip sure form care commercial hand term offer determine structure score Produce Person whatever someone among hundred teacher act garden hundred red appear With stock Citizen school answer stock as start number arm real himself Rate notice Under hair low Form avoid task get baby card anyone deep suggest adult Game order road able heavy Police culture reduce teacher third such he She Just your with ahead pick report camera sure choose wife general Hundred present land will Guess within skin Line never friend from Contain edge accept as list Civil drop cost newspaper anything section activity New no arm individual Statement base Build per figure main stay Eat See throw Authority difference last see night across baby firm Company So source treat computer plant how across news just her me hope without include news seem difficult after low yet style parent picture clear subject during true office owner but turn can war never see long cell so list current top her end May interest course list figure start least risk need network mention Floor camera inside he Himself how under Girl Behavior Through Practice analysis enter region very next Behavior under central cause hand Whole situation detail knowledge Successful institution task lay attack Prove ten participant Physical woman religious Her should friend Blue though throw claim deep item Ask who Several finally national candidate serve officer East month operation peace Ten street loss kind prepare attack against experience Institution toward course Dinner build impact final Rise find arrive hold Understand Others story close citizen main six region tree sometimes choice apply data student trial get food discuss production country husband quality finally eye in beautiful lose lay Sister whom thus between still Top management Fact color such
输出:
[9, 5, 6, 5, 5, 9, 6, 9, 6, 6, 6, 6, 4, 4, 8, 4, 4, 3, 8, 5, 4, 8, 3, 6, 7, 3, 3, 10, 3, 8, 7, 7, 4, 5, 8, 4, 3, 7, 6, 8, 2, 6, 7, 6, 4, 3, 4, 4, 4, 4, 4, 10, 4, 4, 5, 9, 9, 5, 7, 6, 8, 7, 5, 7, 7, 3, 6, 7, 3, 6, 4, 5, 7, 6, 6, 5, 2, 5, 6, 3, 4, 7, 4, 6, 5, 4, 3, 4, 5, 4, 3, 4, 4, 6, 4, 7, 5, 4, 5, 4, 4, 5, 6, 7, 6, 7, 5, 4, 2, 3, 4, 4, 4, 5, 4, 6, 6, 4, 6, 4, 7, 7, 7, 4, 4, 5, 6, 4, 4, 5, 6, 4, 7, 4, 6, 2, 4, 5, 4, 4, 9, 8, 7, 8, 3, 2, 3, 10, 9, 4, 5, 3, 6, 4, 4, 3, 3, 5, 9, 10, 4, 3, 5, 6, 4, 4, 7, 2, 6, 5, 8, 5, 3, 6, 4, 4, 3, 2, 4, 7, 7, 4, 4, 9, 5, 3, 3, 5, 6, 7, 5]
总和 = 999,没有达到应有的 1000
如果您使用的文本参数中有以空格分隔的单词,您可以像下面那样做
def countLetters(sentence):#split your sentence to get the individual words
words=sentence.split(" ")
store=[]#declare an array to hold the length of each word
summation=0 #variable to hold the total number of letters in the text
for word in words:
store.append(len(word))
summation+=len(word) #pile up the total number of letters
if(summation>=1000):
break #break out of the word iteration loop
for i in range(len(words)):#print the words alongside the length of each
print(words[i],store[i])
您可以使用 list comprehension
来实现您的目标:
[len(w) for w in s.split()]
获取其sum()
:
sum([len(w) for w in s.split()])
例子
s = 'authority stuff Design reach speak professor worker Executive future factor police spring live seek specific Easy What lot continue chair area military may matter Mention act bed Government all positive reflect Product plan Check Painting drop bar general weight anything to policy Control series over gas blue trip sure form care commercial hand term offer determine structure score Produce Person whatever someone among hundred teacher act garden hundred red appear With stock Citizen school answer stock as start number arm real himself Rate notice Under hair low Form avoid task get baby card anyone deep suggest adult Game order road able heavy Police culture reduce teacher third such he She Just your with ahead pick report camera sure choose wife general Hundred present land will Guess within skin Line never friend from Contain edge accept as list Civil drop cost newspaper anything section activity New no arm individual Statement base Build per figure main stay Eat See throw Authority difference last see night across baby firm Company So source treat computer plant how across news just her me hope without include news seem difficult after low yet style parent picture clear subject during true office owner but turn can war never see long cell so list current top her end May interest course list figure start least risk need network mention Floor camera inside he Himself how under Girl Behavior Through Practice analysis enter region very next Behavior under central cause hand Whole situation detail knowledge Successful institution task lay attack Prove ten participant Physical woman religious Her should friend Blue though throw claim deep item Ask who Several finally national candidate serve officer East month operation peace Ten street loss kind prepare attack against experience Institution toward course Dinner build impact final Rise find arrive hold Understand Others story close citizen main six region tree sometimes choice apply data student trial get food discuss production country husband quality finally eye in beautiful lose lay Sister whom thus between still Top management Fact color such'
sum([len(w) for w in s.split()])
输出
1794
这里的其他解决方案可能会解决您的作业,但让我们首先看看它失败的原因。
请注意,在循环的第一部分,您要关闭 space 字符以附加当前计数。但是,在计算最后一个单词时,您将始终达到字母总数限制。一旦你从循环中 break
你就不能添加最后一个词(被计算的那个)。
如果您重新安排函数以在将单词添加到计数后检查字母总数,那么您不会丢失最后一个单词。
while True:
if text[index] == " ":
total_counts.append(counter)
counter = 0
index+= 1
if total_letters >= 1000:
break
else:
counter += 1
total_letters += 1
index += 1
然后在跳出循环之前附加字数。
在尝试完成我的一门大学课程时,我遇到了其中一项练习,该练习计算我必须收到的文本中每个单词的字母,直到所有字母的总和 >= 1000,但它永远不会即使文本超过 1000,也会达到 1000。
首先,我认为这可能是因为我没有收到完整的消息,但在查看并弄乱了我创建的不同功能后(none 其中解决了这个问题)它似乎是我的柜台功能不工作。 (这个计数器函数 returns 一个数字数组,稍后我将其转换为字符串)
有什么我没弄明白的东西弄乱了我的代码吗?
def letterCounter(text):
counter = 0
indice = 0
lettTotal = 0
totalCount = []
while True:
if text[indice] == " ":
totalCount.append(counter)
counter = 0
indice += 1
else:
counter += 1
lettTotal += 1
indice += 1
if lettTotal >= 1000:
break
return totalCount
编辑: -样本 输入:
authority stuff Design reach speak professor worker Executive future factor police spring live seek specific Easy What lot continue chair area military may matter Mention act bed Government all positive reflect Product plan Check Painting drop bar general weight anything to policy Control series over gas blue trip sure form care commercial hand term offer determine structure score Produce Person whatever someone among hundred teacher act garden hundred red appear With stock Citizen school answer stock as start number arm real himself Rate notice Under hair low Form avoid task get baby card anyone deep suggest adult Game order road able heavy Police culture reduce teacher third such he She Just your with ahead pick report camera sure choose wife general Hundred present land will Guess within skin Line never friend from Contain edge accept as list Civil drop cost newspaper anything section activity New no arm individual Statement base Build per figure main stay Eat See throw Authority difference last see night across baby firm Company So source treat computer plant how across news just her me hope without include news seem difficult after low yet style parent picture clear subject during true office owner but turn can war never see long cell so list current top her end May interest course list figure start least risk need network mention Floor camera inside he Himself how under Girl Behavior Through Practice analysis enter region very next Behavior under central cause hand Whole situation detail knowledge Successful institution task lay attack Prove ten participant Physical woman religious Her should friend Blue though throw claim deep item Ask who Several finally national candidate serve officer East month operation peace Ten street loss kind prepare attack against experience Institution toward course Dinner build impact final Rise find arrive hold Understand Others story close citizen main six region tree sometimes choice apply data student trial get food discuss production country husband quality finally eye in beautiful lose lay Sister whom thus between still Top management Fact color such
输出:
[9, 5, 6, 5, 5, 9, 6, 9, 6, 6, 6, 6, 4, 4, 8, 4, 4, 3, 8, 5, 4, 8, 3, 6, 7, 3, 3, 10, 3, 8, 7, 7, 4, 5, 8, 4, 3, 7, 6, 8, 2, 6, 7, 6, 4, 3, 4, 4, 4, 4, 4, 10, 4, 4, 5, 9, 9, 5, 7, 6, 8, 7, 5, 7, 7, 3, 6, 7, 3, 6, 4, 5, 7, 6, 6, 5, 2, 5, 6, 3, 4, 7, 4, 6, 5, 4, 3, 4, 5, 4, 3, 4, 4, 6, 4, 7, 5, 4, 5, 4, 4, 5, 6, 7, 6, 7, 5, 4, 2, 3, 4, 4, 4, 5, 4, 6, 6, 4, 6, 4, 7, 7, 7, 4, 4, 5, 6, 4, 4, 5, 6, 4, 7, 4, 6, 2, 4, 5, 4, 4, 9, 8, 7, 8, 3, 2, 3, 10, 9, 4, 5, 3, 6, 4, 4, 3, 3, 5, 9, 10, 4, 3, 5, 6, 4, 4, 7, 2, 6, 5, 8, 5, 3, 6, 4, 4, 3, 2, 4, 7, 7, 4, 4, 9, 5, 3, 3, 5, 6, 7, 5]
总和 = 999,没有达到应有的 1000
如果您使用的文本参数中有以空格分隔的单词,您可以像下面那样做
def countLetters(sentence):#split your sentence to get the individual words
words=sentence.split(" ")
store=[]#declare an array to hold the length of each word
summation=0 #variable to hold the total number of letters in the text
for word in words:
store.append(len(word))
summation+=len(word) #pile up the total number of letters
if(summation>=1000):
break #break out of the word iteration loop
for i in range(len(words)):#print the words alongside the length of each
print(words[i],store[i])
您可以使用 list comprehension
来实现您的目标:
[len(w) for w in s.split()]
获取其sum()
:
sum([len(w) for w in s.split()])
例子
s = 'authority stuff Design reach speak professor worker Executive future factor police spring live seek specific Easy What lot continue chair area military may matter Mention act bed Government all positive reflect Product plan Check Painting drop bar general weight anything to policy Control series over gas blue trip sure form care commercial hand term offer determine structure score Produce Person whatever someone among hundred teacher act garden hundred red appear With stock Citizen school answer stock as start number arm real himself Rate notice Under hair low Form avoid task get baby card anyone deep suggest adult Game order road able heavy Police culture reduce teacher third such he She Just your with ahead pick report camera sure choose wife general Hundred present land will Guess within skin Line never friend from Contain edge accept as list Civil drop cost newspaper anything section activity New no arm individual Statement base Build per figure main stay Eat See throw Authority difference last see night across baby firm Company So source treat computer plant how across news just her me hope without include news seem difficult after low yet style parent picture clear subject during true office owner but turn can war never see long cell so list current top her end May interest course list figure start least risk need network mention Floor camera inside he Himself how under Girl Behavior Through Practice analysis enter region very next Behavior under central cause hand Whole situation detail knowledge Successful institution task lay attack Prove ten participant Physical woman religious Her should friend Blue though throw claim deep item Ask who Several finally national candidate serve officer East month operation peace Ten street loss kind prepare attack against experience Institution toward course Dinner build impact final Rise find arrive hold Understand Others story close citizen main six region tree sometimes choice apply data student trial get food discuss production country husband quality finally eye in beautiful lose lay Sister whom thus between still Top management Fact color such'
sum([len(w) for w in s.split()])
输出
1794
这里的其他解决方案可能会解决您的作业,但让我们首先看看它失败的原因。
请注意,在循环的第一部分,您要关闭 space 字符以附加当前计数。但是,在计算最后一个单词时,您将始终达到字母总数限制。一旦你从循环中 break
你就不能添加最后一个词(被计算的那个)。
如果您重新安排函数以在将单词添加到计数后检查字母总数,那么您不会丢失最后一个单词。
while True:
if text[index] == " ":
total_counts.append(counter)
counter = 0
index+= 1
if total_letters >= 1000:
break
else:
counter += 1
total_letters += 1
index += 1
然后在跳出循环之前附加字数。