编写一个名为'string_type'的函数,它接受一个字符串参数并确定它是什么类型的字符串。
如果字符串为空,则返回“empty”。
如果字符串是单个字符,则返回“character”。
如果字符串代表单个单词,则返回“单词”。如果字符串没有空格,则该字符串是单个单词。
如果字符串是整个句子,则返回“句子”。如果字符串包含空格,则该字符串是句子,但最多只有一个句点。
如果字符串是段落,则返回“段落”。如果字符串包含空格和多个句点,则该字符串是一个段落(我们不会担心其他标点符号)。
如果字符串是多个段落,则返回“page”。如果字符串包含任何换行符(“\ n”),则该字符串是段落。
我被允许使用Python 3的内置字符串函数(例如,len,count等)
我已经能够编写具有不同条件的函数。起初,我尝试按照问题中列出的顺序执行条件,但是,我没有得到与我的测试用例匹配的答案。然后我将条件从条件开始反转,以检查字符串是否为页面,然后是段落等。
def string_type(a_string):
if a_string.count("\n") >= 1:
return "page"
elif a_string.count("") >= 1 and a_string.count(".") > 1:
return "paragraph"
elif len(a_string) > 1 and a_string.count("") > 1 and a_string.count(".") == 1:
return "sentence"
elif len(a_string) > 1 and a_string.count("") == 0:
return "word"
elif len(a_string) == 1:
return "character"
else:
return "empty"
下面是一些将测试您的功能的代码行。您可以更改变量的值以使用不同的输入测试您的函数。
#empty
#character
#word
#sentence
#paragraph
#page
print(string_type(""))
print(string_type("!"))
print(string_type("CS1301."))
print(string_type("This is too many cases!"))
print(string_type("There's way too many ostriches. Why are there so many ostriches. The brochure said there'd only be a few ostriches."))
print(string_type("Paragraphs need to have multiple sentences. It's true.\nHowever, two is enough. Yes, two sentences can make a paragraph."))
当我运行当前代码时,我得到以下结果:
#empty
#character
#sentence (instead of word)
#empty (instead of sentence)
#paragraph
#page
我一直在调整我的单词和句子条件,但是,我还没弄清楚如何纠正。对我做错了什么以及如何修复的任何解释都表示赞赏。
您在字符串中搜索空格的地方是错误的。
elif a_string.count("") >= 1
这将尝试在输入中找到空字符串qazxsw poi - 它显然会找到它。
那部分(和其他人)应该是:
""
请注意它是elif a_string.count(" ") >= 1
- 空间。