[英]How do I complete the 8.4.13 Owls, Part 2 problem in CodeHS Python?
[英]How do I use the enumerate function for CodeHS 8.4.13: Owls, Part 2?
这是我应该做的:
该计划是您之前的“猫头鹰”计划的扩展。 你可以在这里找到你以前的程序!
除了只报告包含单词 owl 的单词数量之外,您还应该报告单词出现的索引!
以下是您的程序运行示例:
Enter some text: Owls are so cool! I think snowy owls might be my favorite. Or maybe spotted owls.
有3个词包含“猫头鹰”。 它们出现在索引处:
[0, 7, 15]
正如您从输出中看到的那样,您必须使用另一个列表来存储找到包含“owl”的单词的索引。枚举函数也可能派上用场!
这是我现在的代码:
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()
工作原理。 我会把研究那部分留给你。
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 "They occured at indices: "
for c, value in enumerate(text, 1):
print(c, value)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.