繁体   English   中英

从字典打印

[英]Printing from a dictionary

对于学校的家庭作业,我们必须编写代码来执行以下操作:

编写程序以测试您对动物科学名称的了解。 您的程序应从animal.txt中读取这些科学的动物名称,然后要求用户输入多行。 下面显示了animals.txt示例:

 Arachnocampa luminosa,Glow Worm Pongo abelii,Sumatran Orang-utan Felis Lynx,Lynx Spheniscus Humboldti,Humboldt Penguin 

animals.txt将包含零行或更多行,每行描述一个动物。 每行包含两个值,以逗号(,)分隔。 逗号的左侧包含动物的科学名称,逗号的右侧包含动物的通用名称。

您的程序应从animal.txt中读取这些科学的动物名称,然后要求用户输入多行。 每次,程序都应要求用户输入动物的科学名称。 如果您从animal.txt读取的数据中存在该科学名称,则程序应打印出该动物的通用名称。 否则,如果科学名称未知,则您的程序应打印出它不知道该动物的信息。 例如:

 Scientific name: Spheniscus Humboldti That's the Humboldt Penguin! Scientific name: Callithrix Pygmaea I don't know that animal. Scientific name: Arachnocampa luminosa That's the Glow Worm! Scientific name: 

以下是我到目前为止编写的代码。 就像您在示例中看到的那样,如果该动物在列表中,那么它应该打印出该动物的通用名称(而不是科学名称)。 当我运行我的代码时,在示例中,它会正确打印出前两个代码,但是当我输入“ Arachnocampa luminosa”时,它会给出“ That's Humbolt Penguin”。

animals = {}

for i in open('animals.txt'):
  sName, cName = i.split(',')
  animals[sName] = cName

x = input('Scientific name: ')

while x:
  if x in animals:
    print("That's the " + cName.rstrip() + "!")
  else:
    print("I don't know that animal.")
  x = input('Scientific name: ')

我在做错什么导致此错误,我该如何解决?

您做错了,您总是打印从.txt - cName读取的最后一个值。 您应该从字典中获取有关科学名称的通用名称的信息。 范例-

while x:
  if x in animals:
    print("That's the " + animals[x].rstrip() + "!")

还有一些建议,循环遍历-

for i in open('animals.txt'):

您应该显式打开和关闭文件,您可以在此处使用with语句。 范例-

with open('animals.txt') as f:
    for i in f:
        sName, cName = i.split(',')
        animals[sName] = cName

with语句将在块结束时为您处理文件的关闭。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM