我需要编写一个程序,要求用户提供一些文本,然后检查单词“owl”在其中重复了多少次。如果这个词包含在另一个词中,这个程序也应该计算这个词。前“hellowl”应该返回;单词“owl”重复了1次。你知道吗
我试过使用.find(),但我收到一条错误消息,如果有人能告诉我如何正确实现它,我将不胜感激。 我当前的代码可以工作,但是如果owl是在上面的例子中提到的另一个单词中说的,则不计算在内
user = str(input("Enter some text: "))
user = user.lower()
user = user.split()
# Counts how many times the word "owl" is said
def owl_count(user):
count = 0
for x in user:
if x == "owl":
count = count + 1
return count
print "There were " + str(owl_count(user)) + " words that contained \"owl\"."
如果用户输入“I like eatingowls”,则输出应该是“有1个单词包含“owl”,但它返回0
代码有
if x == "owl"
,因此代码只统计等于到“owl”的单词。你知道吗如果要检查包含“owl”的单词,请改用
if "owl" in x
。你知道吗如果使用
split
,则只有当owl
用作单词时,而不是在单词内部时,才会得到匹配。你能做的是或者直接使用python的
count
相关问题 更多 >
编程相关推荐