Frage

I am working a lot with MusicXML files and am trying to compile a list of the bars in which there are key changes in a number of pieces. I am in need of some help using python to first identify where the <key> tags occur in the XML file, and then extracting the number from the <measure number ='*'> tag above. Here is an example of a measure I am working with:

<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>

How can I extract the '30' bit? Is there a quick and easy way to do this with music21?

War es hilfreich?

Lösung

In music21 you could do this:

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

for the simple case that you're interested in, John K's answer will do great. But if you want to do something more complex (such as determine the current meter at the time of a key change, see if key regions analyze to the same key as the signature, etc.) then music21 could be an aid.

(EDIT: to disclose that I am the producer of the software package).

Andere Tipps

I don't know Music21. If you want to analyze the XML directly, you could do it with this one-line XPath query:

//measure[attributes/key]/@number

This finds <measure> elements that have <key> elements inside of them and then extracts the number attributes from those measures. See this question for information on doing XPath in Python (it sounds like lxml is the way to go).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top