ValueError:数组必须都是相同长度的Python 3 JSON文件

2024-09-27 00:20:03 发布

您现在位置:Python中文网/ 问答频道 /正文

这个问题我在这里已经看过好几次了。但没有一个解决方案能真正让我走出这个路障。我试图从生成的JSON文件中获取数据,并将其放入单个CSV文件中。这是我的代码:

#all imports should be at the top
import csv
import os 
import pandas as pd
import lyricsgenius as genius

#input client access token from Genius api
api = genius.Genius ("")
#Put name of artist and number of songs you want to search
artist = api.search_artist("Queen", max_songs=5)

os.getcwd()
artist.save_lyrics()
#be sure to change name of artist here after Lyrics_
Artist=pd.read_json("Lyrics_Queen.json")

#Create an empty dictionary to store your songs and related data
artist_dict = {}
def collectSongData(adic):
    dps = list()
    title = adic['title'] #song title
    url = adic['raw']['url'] #spotify url
    artist = adic['artist'] #artist name(s)
    song_id = adic['raw']['id'] #spotify id
    lyrics = adic['lyrics'] #song lyrics
    year = adic['year'] #release date
    upload_date = adic['raw']['description_annotation']['annotatable']['client_timestamps']['lyrics_updated_at'] #lyrics upload date
    annotations = adic['raw']['annotation_count'] #total no. of annotations
    descr = adic['raw']['description'] #song descriptions
    
    dps.append((title,url,artist,song_id,lyrics,year,upload_date,annotations,descr)) #append all to one tuple list
    artist_dict[title] = dps #assign list to song dictionary entry named after song title
    
collectSongData(Artist['songs'][5]) #check function works

def updateCSV_file():
    upload_count = 0 #Set upload counter
    location = r"D:\testlyrics" #Pick file location
    filename = input('Input filename of song file') #give your file a name
    if not filename.strip():
        filename = 'QueenTest.csv'
    elif not filename.endswith('.csv'):
        filename += '.csv'
    full_path = os.path.join(location, filename)
    # to help with debugging
    print(f'saving to {full_path}')
    with open(full_path, 'w', newline='', encoding='utf-8') as file: #open a new csv file
        a = csv.writer(file, delimiter=',') #split by comma
        #(title,url,artist,song_id,lyrics,year,upload_date,annotations,descr)
        headers = ["Title","URL","Artist", "Song ID", "Lyrics", "Year", "Upload Date", "Annotations","Description"] #create header row
        a.writerow(headers) #add header row
        for song in artist_dict:
            a.writerow(artist_dict[song][0])
            upload_count+=1

        print(f"{upload_count} songs have been uploaded")
updateCSV_file()

这里是命令提示符,所有东西都会崩溃

Traceback (most recent call last):
  File "./test4.py", line 15, in <module>
    Artist=pd.read_json("Lyrics_Queen.json")
  File "C:\Users\hunve\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\util\_decorators.py", line 199, in wrapper
    return func(*args, **kwargs)
  File "C:\Users\hunve\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\util\_decorators.py", line 296, in wrapper
    return func(*args, **kwargs)
  File "C:\Users\hunve\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\io\json\_json.py", line 618, in read_json
    result = json_reader.read()
  File "C:\Users\hunve\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\io\json\_json.py", line 755, in read
    obj = self._get_object_parser(self.data)
  File "C:\Users\hunve\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\io\json\_json.py", line 777, in _get_object_parser
    obj = FrameParser(json, **kwargs).parse()
  File "C:\Users\hunve\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\io\json\_json.py", line 886, in parse
    self._parse_no_numpy()
  File "C:\Users\hunve\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\io\json\_json.py", line 1118, in _parse_no_numpy
    self.obj = DataFrame(
  File "C:\Users\hunve\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\frame.py", line 467, in __init__
    mgr = init_dict(data, index, columns, dtype=dtype)
  File "C:\Users\hunve\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py", line 283, in init_dict
    return arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype)
  File "C:\Users\hunve\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py", line 78, in arrays_to_mgr
    index = extract_index(arrays)
  File "C:\Users\hunve\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py", line 397, in extract_index
    raise ValueError("arrays must all be same length")
ValueError: arrays must all be same length

我能够获得正确存储在JSON文件中的所有信息。它只是把它放到一个CSV文件中,在那里我遇到了这个问题


Tags: inpyjsonpandassongartistliblocal

热门问题