提取MusicXML中调性变化的小节编号

1 投票
2 回答
519 浏览
提问于 2025-04-17 17:15

我正在处理很多MusicXML文件,想要整理出一些乐曲中调性变化的段落。我需要一些帮助,使用Python来首先找到XML文件中出现的<key>标签,然后提取上面<measure number ='*'>标签中的数字。以下是我正在处理的一个小节的例子:

<measure number='30' implicit='yes'>
    <print new-page='yes'/>
    <barline location='left'>
        <bar-style>heavy-light</bar-style>
        <repeat direction='forward'/>
    </barline>
    <attributes>
        <key>
            <fifths>-1</fifths>
            <mode>major</mode>
        </key>
    </attributes>
    <direction>
        <direction-type>
            <dynamics  default-y='-82'>
                <p/>
            </dynamics>
        </direction-type>
        <staff>1</staff>
    </direction>
    <direction>
        <direction-type>
            <words default-y='15' relative-x='4'>
        </direction-type>
        <staff>1</staff>
    </direction>
    <note>
        <pitch>
            <step>F</step>
            <octave>5</octave>
        </pitch>
        <duration>768</duration>
        <voice>1</voice>
        <type>quarter</type>
        <stem>down</stem>
        <staff>1</staff>
        <notations>
            <ornaments>
                <trill-mark default-y='20'/>
                <wavy-line type='start' number='1'/>
                <wavy-line type='stop' number='1'/>
            </ornaments>
        </notations>
    </note>
</measure>

我该如何提取出'30'这个数字呢?有没有简单快捷的方法可以用music21来实现?

2 个回答

1

我对Music21不太了解。如果你想直接分析XML文件,可以用这一行简单的XPath查询来实现:

//measure[attributes/key]/@number

这个查询会找到包含<key>元素的<measure>元素,然后提取这些小节的number属性。想了解如何在Python中使用XPath,可以查看这个问题(听说使用lxml是个不错的选择)。

1

在music21这个工具里,你可以这样做:

from music21 import *
s = converter.parse(filepath)
# assuming key changes are the same in all parts, just get the first part
p = s.parts[0]
pFlat = p.flat
keySigs = pFlat.getElementsByClass('KeySignature')
for k in keySigs:
    print k.measureNumber

对于你感兴趣的简单情况,John K的回答已经很好了。但是如果你想做一些更复杂的事情,比如在调性变化时确定当前的拍子,或者检查某个调性区域是否和乐谱上的调性一致等等,那么music21可以帮上忙。

(补充说明:我其实是这个软件包的制作人)。

撰写回答