我正在 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(“嗨大卫”)
添加回答
举报
0/150
提交
取消