Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 类型错误:';在<;字符串>';需要字符串作为左操作数,而不是类型_Python_Json_Python 3.x_Api - Fatal编程技术网

Python 类型错误:';在<;字符串>';需要字符串作为左操作数,而不是类型

Python 类型错误:';在<;字符串>';需要字符串作为左操作数,而不是类型,python,json,python-3.x,api,Python,Json,Python 3.x,Api,我在为高中cs班编写作业时遇到了一个问题。我是python新手,所以如果我在解释我的程序或错误时出错,请原谅我。此外,我确信我可以做很多事情来优化我的程序,但我还是新手 该程序基本上使用命令行菜单来操作API中的数据。节目如下: import requests import json import wikipedia #from datetime import datetime response = requests.get("https://data.nasa.gov/resour

我在为高中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
回溯(最近一次呼叫最后一次):
文件“C:\Users\************\api_project.py”,第109行,在
启动_接口()
文件“C:\Users\************\api\u project.py”,第87行,在start\u界面中
全部打印
文件“C:\Users\************\api\u project.py”,第31行,全部打印
所有名称=获取陨石(类型)
文件“C:\Users\************\api_project.py”,第15行,在get_陨石中
名称=[mtrt[“名称”]用于meteorite_页面中的mtrt,如果键入mtrt[“recclass”]]
文件“C:\Users\************\api_project.py”,第15行,在
名称=[mtrt[“名称”]用于meteorite_页面中的mtrt,如果键入mtrt[“recclass”]]
TypeError:“in”需要字符串作为左操作数,而不是类型
以及运行选项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'
回溯(最近一次呼叫最后一次):
文件“C:\Users\************\api_project.py”,第106行,在
启动_接口()
文件“C:\Users\************\api\u project.py”,第89行,在start\u界面中
按年份排序()
文件“C:\Users\************\api\u project.py”,第41行,按年份排序
所有年份=按功能排序(“年份”)
文件“C:\Users\************\api\u project.py”,第20行,按功能排序
特征=[mtrt[“年”]用于陨石中的mtrt\u页]
文件“C:\Users\************\api_project.py”,第20行,在
特征=[mtrt[“年”]用于陨石中的mtrt\u页]
关键错误:“年”
对于选项3和选项4,关键误差分别在“年”和“质量”之间变化。
任何帮助都将不胜感激,我将尽我所能回答所有问题。

问题是因为你写了

all_names = get_meteorites(type)
这应该是

all_names = get_meteorites("all")

因为默认值是“全部”

其他错误是因为一些陨石缺少
年份
质量
属性。您需要将该检查添加到列表中

def sort_by_feature(recclass):
    if recclass == "year":
        feature = [mtrt["year"] for mtrt in meteorite_page if "year" in mtrt]
    else:
        feature = [mtrt["mass"] for mtrt in meteorite_page if "mass" in mtrt]
        
    return feature

这只会跳过没有指定功能的陨石。

如果mtrt[“recclass”]中键入,那么
应该是什么意思?不要使用
type
作为变量名,它是保存类型层次结构基础的内置不变量的名称。问题在于:
所有名称=获取陨石(type)
您从未分配过
类型
,因此它使用全局变量。我想你想要
all\u name=get\u meteorites(“all”)
如果type等于string?编辑:看看Barmar的答案。@Barmar-是的,这似乎解决了其中一个问题。我把“type”的所有实例都改成了“recclass”,我把“get_meteorites(type)”改成了“all”,就像你说的。但当我尝试选项3和4时,仍然会出现关键错误。
def sort_by_feature(recclass):
    if recclass == "year":
        feature = [mtrt["year"] for mtrt in meteorite_page if "year" in mtrt]
    else:
        feature = [mtrt["mass"] for mtrt in meteorite_page if "mass" in mtrt]
        
    return feature