Python 首次使用pickle.dump/pickle.load

Python 首次使用pickle.dump/pickle.load,python,neural-network,pickle,music21,Python,Neural Network,Pickle,Music21,我正在使用一个函数,在它结束时,它将数据转储到一个pickle文件中,稍后我调用我的函数,它工作正常。我希望使用我创建的数据,而不是调用函数。我试过使用pickle.load,但似乎不起作用 职能: def get_notes(): """ Get all the notes and chords from the midi files in the directory """ notes = [] for file in midi_

我正在使用一个函数,在它结束时,它将数据转储到一个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 = prepare_sequences(notes, n_vocab)

model = create_network(network_input, n_vocab)

train(model, network_input, network_output)

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

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

您可以找到更多信息。

当“它似乎不起作用”时,它会做什么?有错误吗?
pickle.load
采用文件对象而不是文件路径,就像
pickle.dump
一样。阅读文档:)music21的v.7应该在今年夏天或秋天推出,它将更好地解析MIDI文件,这样您就不必调用
乐器。partitionByInstrument
——这可能是瓶颈所在。music21已经尝试通过清除
转换器的结果来帮助您。parse
——如果您进行挖掘,您将看到必须肯定地将参数
forceSource=False
发送到
转换器。parse
以使其不从磁盘加载已清除的结果。