music21并行解析文件

时间:2018-07-16 21:37:07

标签: python music21

我想使用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]

效果很好

1 个答案:

答案 0 :(得分:2)

在这一行:

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

因为将()放在函数名称之后,所以您没有传递函数本身,而是传递了调用该函数的结果。只需将其更改为:

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

那样,您将实际函数作为参数传递。