猿问

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

我正在 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。如果遇到错误,我写了一个返回“不是字符串”的except


def 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: 4

Word Count: 2

Word Count: Not a string

Word Count: Not a string

Word Count: Not a string


print("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: 4

Word Count: 4

Word Count: Not a string

Word Count: Not a string

Word Count: Not a string

我不知道如何调整我的代码来解释测试用例 2(“嗨大卫”)


慕丝7291255
浏览 175回答 1
1回答

慕码人8056858

至少有两个选择:替换所有双空格,直到开始计数之前只有一个空格跟踪,前一个字符是什么并添加额外的条件
随时随地看视频慕课网APP

相关分类

Python
我要回答