【发布时间】:2021-04-30 19:20:49
【问题描述】:
我在为我的高中 CS 课编写作业时遇到了问题。我是python的新手,所以如果我在解释我的程序或错误时犯了任何错误,请原谅我。另外,我确信我可以做很多事情来优化我的程序,但我还是个新手。
该程序本质上使用命令行菜单来操作 API 内的数据。这是程序:
import requests
import json
import wikipedia
#from datetime import datetime
response = requests.get("https://data.nasa.gov/resource/y77d-th95.json")
meteorite_page = json.loads(response.text)
# Helper Functions
def get_meteorites(type = "all"):
if type == "all":
names = [mtrt["name"] for mtrt in meteorite_page]
else:
names = [mtrt["name"] for mtrt in meteorite_page if type in mtrt["recclass"]]
return names
def sort_by_feature(type):
if type == "year":
feature = [mtrt["year"] for mtrt in meteorite_page]
else:
feature = [mtrt["mass"] for mtrt in meteorite_page]
return feature
# Choice functions
def print_all():
all_names = get_meteorites(type)
for index, name in enumerate(all_names):
print(f"{index + 1}: {name}")
print(all_names)
def print_by_class():
type = input("Enter a class (See this page for classification names/details --> stackoverflow made me take out this link): ").upper()
all_names = get_meteorites(type)
print(f"All {type} meteorites: ")
for index, name in enumerate(all_names):
print(f"{index + 1}: {name}")
def sort_by_year():
all_years = sort_by_feature("year")
for index, year in enumerate(all_years):
print(f"{index + 1}: {year}")
print(all_years)
def sort_by_mass():
all_masses = sort_by_feature("mass")
for index, mass in enumerate(all_masses):
print(f"{index + 1}: {mass}")
print(all_masses)
def meteorite_data():
meteorite_name = input("Enter the name of a meteorite: ")
for mtrt in meteorite_page:
if meteorite_name in mtrt['name']:
for key in mtrt:
print(f"{key}: {mtrt[key]}")
print("Wikipedia Summary: ")
try:
print(wikipedia.summary(f"{meteorite_name} (meteorite)"))
except:
print("No Wikipedia page could be found.")
# User interface
def start_interface():
print("Meteorite Data Explorer")
print("‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾")
while True:
print("̲M̲e̲n̲u̲ ̲")
print("1. List the names of all Earth meteorite landings")
print("2. See all meteorites in one class")
print("3. Organize meteorites from oldest to newest")
print("4. Organize meteorites from biggest to smallest")
print("5. Access the data of an individual meteorite")
print("0. Quit")
choice = input("Select an option: ")
if choice == "1":
print_all()
elif choice == "2":
print_by_class()
print('')
elif choice == "3":
sort_by_year()
print('')
elif choice == "4":
sort_by_mass()
print('')
elif choice == "5":
meteorite_data()
print('')
elif choice == "0":
print("Exit")
break
else:
print("That is not an option.")
print("‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾")
if __name__ == "__main__":
start_interface()
我收到的错误是选项 1、3 和 4。 我尝试运行选项 1 时的完整错误:
Traceback (most recent call last):
File "C:\Users\*****\*******\api_project.py", line 109, in <module>
start_interface()
File "C:\Users\*****\*******\api_project.py", line 87, in start_interface
print_all()
File "C:\Users\*****\*******\api_project.py", line 31, in print_all
all_names = get_meteorites(type)
File "C:\Users\*****\*******\api_project.py", line 15, in get_meteorites
names = [mtrt["name"] for mtrt in meteorite_page if type in mtrt["recclass"]]
File "C:\Users\*****\*******\api_project.py", line 15, in <listcomp>
names = [mtrt["name"] for mtrt in meteorite_page if type in mtrt["recclass"]]
TypeError: 'in <string>' requires string as left operand, not type
当我运行选项 3 和 4 时出现完整错误:
Traceback (most recent call last):
File "C:\Users\*****\*******\api_project.py", line 106, in <module>
start_interface()
File "C:\Users\*****\*******\api_project.py", line 89, in start_interface
sort_by_year()
File "C:\Users\*****\*******\api_project.py", line 41, in sort_by_year
all_years = sort_by_feature("year")
File "C:\Users\*****\*******\api_project.py", line 20, in sort_by_feature
feature = [mtrt["year"] for mtrt in meteorite_page]
File "C:\Users\*****\*******\api_project.py", line 20, in <listcomp>
feature = [mtrt["year"] for mtrt in meteorite_page]
KeyError: 'year'
对于选项 3 和 4,KeyError 分别在 'year' 和 'mass' 之间变化。 任何帮助将不胜感激,我将尽我所能回答所有问题。
【问题讨论】:
-
if type in mtrt["recclass"]应该是什么意思? -
不要使用
type作为变量名,它是一个包含类型层次基础的内置不变量的名称。 -
问题出在这里:
all_names = get_meteorites(type)你从来没有分配过type,所以它使用了全局变量。我想你想要all_names = get_meteorites("all") -
如果类型等于字符串?编辑:看看 Barmar 的答案。
-
@Barmar - 是的,这似乎解决了其中一个问题。我将“type”的所有实例更改为“recclass”,在我调用“get_meteorites(type)”的地方,我将“type”更改为“all”,就像你说的那样。但是当我尝试选项 3 和 4 时,我仍然收到 KeyError。
标签: python json python-3.x api