为了账号安全,请及时绑定邮箱和手机立即绑定

如果单词之间有多个空格,如何确保计算字符串中正确的单词数?

如果单词之间有多个空格,如何确保计算字符串中正确的单词数?

慕丝7291255 2021-12-16 15:53:49
我正在 Python 3 中编写一个名为 word_count 的函数(它接受一个我称之为 my_string 的参数),它应该计算字符串中的单词数。字符串可能包含多个空格的单词(例如 hello there),并且该函数需要能够计算出它是两个单词。我不应该使用任何内置的 Python 函数,如果我遇到任何错误,我也会使用 try-except(例如,如果感兴趣的值不是字符串,除了将执行返回“不是字符串” ”我已经能够编写一个函数,并且我创建了一个名为 numspaces 的计数器变量,我已将其初始化为 0。然后我写了 try,然后是一个带有名为 current_character 的索引变量的 for 循环,它将遍历 my_string 中的所有当前字符. 我写了一个条件语句,如果 current_character 等于一个空格,numspaces 需要加一,numwords(我用来保持字符串中单词总数的变量)等于 numspaces + 1。然后我写一个 else if 语句,表示如果 numspaces 等于 0,numwords = 1 并返回 numwords。如果遇到错误,我写了一个返回“不是字符串”的exceptdef word_count(my_string):    numspaces = 0    try:       for current_character in my_string:        if current_character == " ":            numspaces += 1            numwords = numspaces + 1        elif numspaces == 0:            numwords = 1       return numwords    except:       return "Not a string"以下是一些测试用例,以及使用测试用例时的预期结果:Word Count: 4Word Count: 2Word Count: Not a stringWord Count: Not a stringWord Count: Not a stringprint("Word Count:", word_count("Four words are here!"))print("Word Count:", word_count("Hi   David"))print("Word Count:", word_count(5))print("Word Count:", word_count(5.1))print("Word Count:", word_count(True))当我运行我编写的代码时,我得到以下输出:Word Count: 4Word Count: 4Word Count: Not a stringWord Count: Not a stringWord Count: Not a string我不知道如何调整我的代码来解释测试用例 2(“嗨大卫”)
查看完整描述

1 回答

?
慕码人8056858

TA贡献1803条经验 获得超6个赞

至少有两个选择:

  1. 替换所有双空格,直到开始计数之前只有一个空格

  2. 跟踪,前一个字符是什么并添加额外的条件


查看完整回答
反对 回复 2021-12-16
  • 1 回答
  • 0 关注
  • 174 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号