第一次使用 pickle.dump / pickle.load

问题描述

我正在使用一个函数,在它结束时,它将数据转储到一个 pickle 文件中,稍后我调用我的函数并且它工作正常。我想使用我创建的数据,而不是调用函数。我尝试使用 pickle.load 但它似乎不起作用。

功能

def get_notes():
""" Get all the notes and chords from the midi files in the directory """
notes = []

for file in midi_files:
    midi = converter.parse(file)

    print("Parsing %s" % file)

    notes_to_parse = None

    try:  # file has instrument parts
        s2 = instrument.partitionByInstrument(midi)
        notes_to_parse = s2.parts[0].recurse()
    except:  # file has notes in a flat structure
        notes_to_parse = midi.flat.notes

    for element in notes_to_parse:
        if isinstance(element,note.Note):
            notes.append(str(element.pitch))
        elif isinstance(element,chord.Chord):
            notes.append('.'.join(str(n) for n in element.normalOrder))

with open('/content/gdrive/MyDrive/notes','wb') as filepath:
    pickle.dump(notes,filepath)

return notes

第二个函数通常是这样的:

def train_network():
""" Train a Neural Network to generate music """
notes = get_notes()

# get amount of pitch names
n_vocab = len(set(notes))

network_input,network_output = prepare_sequences(notes,n_vocab)

model = create_network(network_input,n_vocab)

train(model,network_input,network_output)

但我不想每次训练时都重新解析文件,我需要类似的东西:

def train_network():
""" Train a Neural Network to generate music """
notes = pikle.load('/content/gdrive/MyDrive/notes')

# get amount of pitch names
n_vocab = len(set(notes))

network_input,network_output)

解决方法

正如@MarkTolonen 也提到的,pickle.load 不采用文件路径,而是从打开的文件中提取一个对象。试试这个:

with open('/content/gdrive/MyDrive/notes',mode) as f:
    notes = pickle.load(f)

您可以找到更多 herehere