音乐21包括音符转换计数器吗?

2024-04-28 05:32:23 发布

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

我试着在给定的旋律中得到音调之间的转换率(只有名字,没有八度)。 例如,如果我的旋律音高是(按顺序)C D E D F C B C,我应该得到C-D转换以0.5的速率发生,B-C的速率为1,等等

我应该能够用Python编写一个函数来实现这一点(可能使用了大量的elifs……),但看起来music21也必须能够轻松地完成这一点。我看了文档,谷歌,还有其他问题。。。我不知道怎么做,但我怀疑我缺少了一个对我来说非常有用的工具箱。你知道吗


Tags: 函数文档顺序速率工具箱名字music21旋律
2条回答

你可能要找的是一种二元表示法,我通常用字典来处理。这可能有点草率,但你可以很容易地整理一下:

note_list = ...a list containing all notes in order
bigram_dict = {}
for note in range(1, len(note_list)):
    bigram = (note -1, note)
    if bigram not in bigram_dict:
        bigram_dict[bigram] = 1 / len(note_list)
    else:
        bigram_dict[bigram] += 1 / len(note_list)

这将为您提供每个二元图的百分比。如果使用Python2.x,则必须使用bigram_dict[bigram += float(1 / len(note_list))来避免整数/浮点问题。另外,如果字典给你带来麻烦,你可以尝试使用defaultdict。你知道吗

我建议你这样做:

from music21.ext.more_itertools import windowed
from collections import Counter
# assuming s is your Stream
nameTuples = []
for n1, n2 in windowed(s.recurse().notes, 2):
    nameTuples.append((n1.name, n2.name))
c = Counter(nameTuples)
totalNotes = len(s.recurse().notes) # py2 cast to float
{k : v / totalNotes for k, v in c.items()}

windowed的优点是很容易创建三叉树等

相关问题 更多 >