gpt4 book ai didi

python - 如何使用 CodeHS 8.4.13 : Owls, 第 2 部分的枚举函数?

转载 作者:行者123 更新时间:2023-12-01 07:51:46 26 4
gpt4 key购买 nike

这就是我应该做的:

This program is an extension of your previous ‘Owls’ program. You can find your previous program here!

In addition to just reporting how many words contained the word owl, you should report the indices at which the words occurred!

Here’s what an example run of your program might look like:

Enter some text: Owls are so cool! I think snowy owls might be my
favorite. Or maybe spotted owls.

There were 3 words that contained "owl". They occurred at indices: [0, 7, 15] As you can see from the output, you’ll have to use another list to store the indices where you found the words containing “owl”.

The enumerate function might also come in handy!

这是我现在的代码:

text = input("Enter some text: ")
text.lower()
text.split()
print "There are " + str(text.count("owl")) + " words that contained \"owl\"."
print "They occured at indices: for c, value in enumerate(text, 1):
print(c, value)

我完全不知道如何使用enumerate函数。我现在使用 enumerate 函数的方式是从其他网站获得的。当我尝试运行此代码时,我得到的第一件事是此错误:

Error: Line 5
ParseError: bad token on line 5

由此,我知道我使用 enumerate 的方式是错误的。但是,我不知道正确的使用方法。

最佳答案

在此行中:

print "They occured at indices: for c, value in enumerate(text, 1):
print(c, value)

您还没有以 " 结束字符串,因此 Python 会不断读取越来越多的内容(假设该字符串还有更多内容),直到它到达文件末尾。您不希望这样,作为部分: for c, value in enumerate(text, 1): 是您希望 Python 执行的命令,它本身并不是您希望 Python 打印的字符串。所以首先我们关闭您的字符串:

print "They occured at indices: "
for c, value in enumerate(text, 1):
print(c, value)

这应该可以消除您的错误,但会打印错误的答案。您在该行中遇到了另一个问题: text.split() 您不了解 split() 的工作原理。我将把这部分的研究留给你。

关于python - 如何使用 CodeHS 8.4.13 : Owls, 第 2 部分的枚举函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56172334/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com