2

我想使用 music21 库并行解析 MIDI 文件,因为有时脚本挂起并且 CPU 加载到 100%。问题是我的函数返回文件中的注释列表,当我使用common.runParallel这个函数时,我得到了TypeError: 'list' object is not callable

from music21 import converter, instrument, note, chord, common

for file in glob.glob("midi/preludes/*.mid"):
    files.append("midi/preludes"+file)


def get_notes():
    notes = []

    midi = converter.parse(file)

    print("Parsing %s" % file)

    notes_to_parse = None

    try:   
        s2 = instrument.partitionByInstrument(midi)
        notes_to_parse = s2.parts[0].recurse()
    except:  
        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):
            print('.'.join(str(n) for n in element.normalOrder))
            notes.append('.'.join(str(n) for n in element.normalOrder))

    with open('data/notes', 'wb') as filepath:
        pickle.dump(notes, filepath)

    return notes

output = common.runParallel(files, parallelFunction=get_notes())

我怎样才能解决这个问题?

EDID

我将功能更改为:

def get_notes_parallel(file):
    notes = []

    midi = converter.parse(file)

    print("Parsing %s" % file)

    notes_to_parse = None

    try:   
        s2 = instrument.partitionByInstrument(midi)
        notes_to_parse = s2.parts[0].recurse()
    except:  
        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):
            print('.'.join(str(n) for n in element.normalOrder))
            notes.append('.'.join(str(n) for n in element.normalOrder))

    with open('data/notes', 'wb') as filepath:
        pickle.dump(notes, filepath)

    return notes

notes = common.runParallel(files, parallelFunction=get_notes_parallel)
notes = [item for list in notes for item in list]

它运行良好

4

1 回答 1

2

在这一行:

output = common.runParallel(files, parallelFunction=get_notes())

因为你()在函数名后面加上了,所以你不是在传递函数本身,而是传递调用函数的结果。只需将其更改为:

output = common.runParallel(files, parallelFunction=get_notes)

这样您就可以将实际函数作为参数传递。

于 2018-07-16T21:44:09.633 回答