Python – Parsing conditional statements

parsingpython

I've written a small utility in Python3 to help me copy my music collection from my NAS to a mobile device. The usefulness of this is that it will auto-convert flac files to ogg-vorbis (to save space) and also exclude some files based on their audio tags (i.e. artist, album, date, etc).

I'm not happy with the limited nature of the exclude feature and I want to improve it but I've hit a mental block and I'm looking for advice on how to proceed.

I would like the user to write an exclude file which will look something like this:

exclude {
    artist is "U2"

    artist is "Uriah Heep" {
        album is "Spellbinder"
        album is "Innocent Victim"
    }
}

This would translate to:

exclude if 
(artist = "U2") OR 
(artist = "Uriah Heep" AND (album = "Spellbinder" OR album = "Innocent Victim"))

There will be more conditionals such as sub-string matching and date ranges.

I've been checking out PLY but I'm struggling with the concepts of how to parse this type of nested structure and also how to represent the resulting conditional so that I can execute it in code when applying the exclude filter during the copy operation.

Best Answer

Language agnostic answer (I don't know python):

Since your structure is a tree, you need to store it as a tree. You need to know whether your tree is going to be only two levels or more, this may affect the way to handle it (recursively or brute force).

If you don't need to optimise for speed you can start with a naive algorithm.
Match your tree with a handling algorithm.
Start from the top level.
1/ Loop for each branch until you find a match (exclusion), if there is no match return to caller with no exclusion.
2/ If the node has no branch at the next level return to caller with an exclusion.
3/ If the node has branches or leaves at the next level, go down one level and start from action 1.

HTH

Related Topic