def songs_pyparsing(fh): r""" >>> import os >>> filename = os.path.dirname(__file__) >>> filename = os.path.join(filename, "data/Various-Pop.m3u") >>> with open(filename, "rt", encoding="utf8") as fh: ... songs = songs_pyparsing(fh) >>> songs[0].title, songs[0].seconds, songs[0].filename ('Various - Two Tribes', 236, 'Various\\Frankie Goes To Hollywood\\02-Two Tribes.ogg') >>> songs[-1].title, songs[-1].seconds, songs[-1].filename ('The Police - Walking On The Moon', 303, 'Various\\Sting & The Police 1997\\06-Walking On The Moon.ogg') >>> lines = [] >>> lines.append("#EXTM3U") >>> lines.append("#EXTINF:140,The Beatles - Love Me Do") >>> lines.append("Beatles\\Greatest Hits\\01-Love Me Do.ogg") >>> lines.append("#EXTINF:-1,The Beatles - From Me To You") >>> lines.append("Beatles\\Greatest Hits\\02-From Me To You.ogg") >>> import io >>> data = io.StringIO("\n".join(lines)) >>> songs = songs_ply(data) >>> len(songs) == 2 True >>> songs[0].title, songs[0].seconds ('The Beatles - Love Me Do', 140) >>> songs[1].title, songs[1].seconds ('The Beatles - From Me To You', -1) """ def add_song(tokens): songs.append(Song(tokens.title, tokens.seconds, tokens.filename)) #songs.append(Song(**tokens.asDict())) songs = [] title = restOfLine("title") filename = restOfLine("filename") seconds = Combine(Optional("-") + Word(nums)).setParseAction( lambda tokens: int(tokens[0]))("seconds") info = Suppress("#EXTINF:") + seconds + Suppress(",") + title entry = info + LineEnd() + filename + LineEnd() entry.setParseAction(add_song) parser = Suppress("#EXTM3U") + OneOrMore(entry) try: parser.parseFile(fh) except ParseException as err: print("parse error: {0}".format(err)) return [] return songs
def pyparse_m3u(file): def add_song(tokens): new_song = M3U_SONG(tokens.title, tokens.seconds, tokens.filename) song_list.append(new_song) song_list = [] title = restOfLine('title') filename = restOfLine('filename') seconds = Combine(Optional('-') + Word(nums)).setParseAction( lambda tokens: int(tokens[0]))('seconds') sec_title = Suppress('#EXTINF:') + seconds + Suppress(',') + title info = LineEnd() + sec_title + LineEnd() + filename info.addParseAction(add_song) parser = Suppress('#EXTM3U') + OneOrMore(info) try: parser.parseFile(file) except ParseException as parse_err: print('Parsing error: {}', parse_err) return [] return song_list