An example of why I like Python

By Confusion on Saturday 11 October 2008 14:29 - Comments (10)
Categories: Python, Software engineering, Views: 28.341

During the past week, the Dutch alternative radiostation Kink FM aired the Kink 1300: the top 1300 songs their listeners wanted to hear. I was interested in finding the most popular bands in the list and wrote a small Python program to do just that. Afterwards, I thought it might be considered a nice example of the expressive power of this generation of scripting languages.

Python:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import re

artists = {}

songs = open("songs")
for line in songs:
    matcher = re.search("\d+\. (.+?) - (.+)", line)
    artist = matcher.group(1)
    song = matcher.group(2)
    if not artist in artists:
        artists[artist] = [song]
    else:
        artists[artist].append(song)

decoratedArtists = [(len(songs), artist) for (artist, songs) in artists.items()]
decoratedArtists.sort(reverse=True)
for (length, artist) in decoratedArtists:
    print length, artist, artists[artist]


Edit: an improved version based on comments (I didn't use the named groups mentioned, but for other purposes they might be quite useful).

code:
1
2
3
4
5
6
7
8
9
10
11
12
13
import re
from collections import defaultdict

artists = defaultdict(list)

for line in open("songs"):
    artist, song = re.search("\d+\. (.+?) - (.+)", line).groups()
    artists[artist].append(song)

decoratedArtists = [(len(songs), artist) for (artist, songs) in artists.items()]
decoratedArtists.sort(reverse=True)
for (length, artist) in decoratedArtists:
    print length, artist, artists[artist]


which results in:
18 Radiohead ['Paranoid Android', 'Street Spirit', 'Exit Music (For A Film)', 'Creep', 'Karma Police', 'Fake Plastic Trees', 'Idioteque', 'Jigsaw Falling Into Place', 'How To Disappear Completely', 'Pyramid Song', 'No Suprises', 'There There', 'My Iron Lung', 'Just', 'Lucky', 'High & Dry', 'Knives Out', 'Optimistic']
14 Red Hot Chili Peppers ['Californication', 'Under The Bridge', 'Scar Tissue', 'Otherside', 'Give It Away', 'Road Tripping', 'By The Way', 'Dani California', 'Suck My Kiss', 'Zephyr Song', 'Knock Me Down', "Can't Stop", 'Around The World', 'Fortune Faded']
13 U2 ['Bad', 'Unforgettable Fire', 'One', 'Beautiful Day', 'I Will Follow', 'Sunday Bloody Sunday', 'With Or Without You', 'Where The Streets Have No Name', 'Fly', 'Vertigo', 'October', 'Pride', "I Still Haven't Found What I'm Looking For"]
13 Muse ['Bliss', 'New Born', 'Knights Of Cydonia', 'Plug In Baby', 'Muscle Museum', 'Starlight', 'Time Is Running Out', 'Hysteria', 'Supermassive Black Hole', 'Sing For Absolution', 'Sunburn', 'Feeling Good', 'Hyper Music']
12 Coldplay ['Clocks', 'The Scientist', 'Yellow', 'Fix You', 'Trouble', 'God Put A Smile Upon Your Face', "Don't Panic", 'Talk', 'In My Place', 'Shiver', 'Speed Of Sound', 'The Hardest Part']
11 Rammstein ['Ich Will', 'Engel', 'Sonne', 'Wolt Ihr Das Bett In Flammen Sehen', 'Mutter', 'Heirate Mich', 'Mein Teil', 'Links 2-3-4', 'Rammstein', 'Keine Lust', 'Amerika']
11 Faith No More ['Epic', 'Digging The Grave', 'Midlife Crisis', 'We Care A Lot', 'Evidence', 'King For A Day', 'Ashes To Ashes', 'Falling To Pieces', 'I Started A Joke', 'Easy', 'Last Cup Of Sorrow']
11 Depeche Mode ['Enjoy The Silence', 'I Feel You', 'Personal Jesus', 'Blasphemous Rumours', 'Precious', 'Barrel Of A Gun', 'A Question Of Lust', 'Everything Counts', "A Pain That I'm Used To", "It's No Good", 'Policy Of Truth']
10 Tool ['Sober', 'Aenima', 'Lateralus', 'Schism', 'Stinkfist', 'Eulogy', 'Vicarious', 'Pushit', 'Parabola', 'Prison Sex']
10 Smiths ['There Is A Light That Never Goes Out', 'How Soon Is Now', 'Bigmouth Strikes Again', 'Panic', "Heaven Knows I'm Miserable Now", 'The Boy With The Thorn In His Side', 'This Charming Man', 'Girlfriend In A Coma', 'William, It Was Really Nothing', 'Shoplifters Of The World Unite']
10 Queens of the Stone Age ['No One Knows', 'Go With The Flow', 'Little Sister', 'The Lost Art Of Keeping A Secret', "3's & 7's", 'Burn The Witch', 'Feel Good Hit Of The Summer', 'Make It With Chu', 'In My Head', 'Sick, Sick, Sick']
10 Pearl Jam ['Black', 'Alive', 'Jeremy', 'Even Flow', 'Daughter', 'Given To Fly', 'Dissident', 'Not For You', 'Do The Evolution', 'I Got Id']
10 Metallica ['One', 'Master Of Puppets', 'Enter Sandman', 'Nothing Else Matters', 'The Unforgiven', 'Wherever I May Roam', 'Until It Sleeps', 'Whiskey In The Jar', 'St. Anger', 'Fuel']
10 Foo Fighters ['Everlong', 'The Pretender', 'Best Of You', 'Monkey Wrench', 'Times Like These', 'Learn To Fly', 'DOA', 'Stacked Actors', 'This Is A Call', 'Walking After You']
10 Deus ['Suds & Soda', 'Roses', 'Hotellounge', 'Instant Street', 'Nothing Really Ends', 'Little Arithmetics', '7 Days, 7 Weeks', 'The Ideal Crash', 'Theme From Turnpike', 'Via']
10 Cure ['A Forest', 'Charlotte Sometimes', 'Lullaby', "Boys Don't Cry", 'In Between Days', 'Killing An Arab', 'Close To Me', "Friday I'm In Love", 'Lovecats', "Why Can't I Be You"]
10 Bjork ['Play Dead', 'Bachelorette', 'Joga', 'Hyperballad', "It's Oh So Quiet", 'Hunter', 'Venus As A Boy', 'Human Behaviour', 'Big Time Sensuality', 'Army Of Me']
9 White Stripes ['Seven Nation Army', 'Icky Thump', 'My Doorbell', 'Dead Leaves And The Dirty Ground', 'The Hardest Button To Button', 'Fell In Love With A Girl', 'Hotel Yorba', "You Don't Know What Love Is", 'Conquest']
9 Smashing Pumpkins ['Disarm', 'Bullet With Butterfly Wings', '1979', 'Today', 'Tonight, Tonight', 'Ava Adore', 'Stand Inside Your Love', 'The End Is The Beginning Is The End', 'Tristessa']
9 REM ['The One I Love', 'Losing My Religion', "It's The End Of The World As We Know It", 'Drive', 'Everybody Hurts', 'So Central Rain', "What's The Frequency Kenneth", 'Finest Worksong', 'Orange Crush']
9 Placebo ['The Bitter End', 'Pure Morning', 'Every You Every Me', 'Twenty Years', 'Nancy Boy', 'Meds', 'Song To Say Goodbye', 'Special K', 'English Summer Rain']
9 Oasis ['Live Forever', 'Wonderwall', "Don't Look Back In Anger", 'Champagne Supernova', 'Acquiesce', 'Some Might Say', 'Whatever', 'Lyla', 'Roll With It']
9 Linkin Park ['In The End', 'One Step Closer', 'Crawling', 'Breaking The Habit', 'Faint', 'Somewhere I Belong', "What I've Done", 'Shadow of the Day', 'Points Of Authority']
9 Incubus ['Drive', 'Megalomaniac', 'Anna Molly', 'Pardon Me', 'I Wish You Were Here', 'Are You In?', 'Nice To Know You', 'Love Hurts', 'Warning']
9 Guns N' Roses ['Estranged', 'November Rain', "Sweet Child O' Mine", 'Paradise City', 'Welcome To The Jungle', "Knockin' On Heavens Door", 'You Could Be Mine', "Don't Cry", 'Patience']
9 Green Day ['Basket Case', 'American Idiot', 'Wake Me Up When September Ends', 'Working Class Hero', 'Boulevard Of Broken Dreams', 'When I Come Around', 'Long View', 'Holiday', 'Jesus Of Suburbia']
9 David Bowie ['Heroes', 'Space Oddity', 'Ziggy Stardust', "Rock'n Roll Suicide", "I'm Deranged", 'Golden Years', 'Starman', 'Absolute Beginners', 'Sound & Vision']
9 Blur ['Song 2', 'Coffee & Tv', 'Parklife', 'Beetlebum', 'The Universal', 'Girls & Boys', "There's No Other Way", 'Charmless Man', 'Tender']
9 Beatles ['A Day In The Life', 'I Am The Walrus', 'Tomorrow Never Knows', 'Happiness Is A Warm', 'Lucy In The Sky With Diamonds', 'The Fool On The Hill', 'Revolution', 'Taxman', 'Get Back']
8 Pink Floyd ['Shine On You Crazy Diamond', 'Wish You Were Here', 'Time', 'The Great Gig In The Sky', 'Welcome To The Machine', 'Another Brick In The Wall', 'Money', 'See Emily Play']
8 Neil Young ['Like A Hurricane', 'Rockin In The Free World', 'Needle And The Damage Done', 'Down By The River', 'My My Hey Hey (Out Of The Blue)', 'Heart Of Gold', 'Southern Man', 'After The Goldrush']
8 Massive Attack ['Unfinished Sympathy', 'Teardrop', 'Angel', 'Protection', 'Risingson', 'Man Next Door', 'Inertia Creeps', 'Safe From Harm']
8 Live ['Lightning Crashes', 'I Alone', "Lakini's Juice", 'Selling The Drama', "The Dolphin's Cry", 'All Over You', 'Run To The Water', 'They Stood Up For Love']
8 Bloc Party ['Banquet', 'Hunting For Witches', 'Helicopter', 'Two More Years', 'The Prayer', 'I Still Remember', 'The Pioneers', 'Flux']
7 Velvet Underground ['Heroin', 'Sunday Morning', "I'm Waiting For The Man", 'Rock & Roll', "All Tomorrow's Parties", 'Femme Fatale', 'Sweet Jane']
7 System Of A Down ['Chop Suey', 'Toxicity', 'Aerials', 'B.Y.O.B.', 'Lonely Day', 'Old School Hollywood', 'Hypnotize']
7 Prodigy ['Smack My Bitch Up', 'No Good', 'Firestarter', 'Voodoo People', 'Out Of Space', 'Breathe', 'Poison']
7 Nirvana ['Smells Like Teen Spirit', 'Lithium', 'Come As You Are', 'Heart-Shaped Box', 'In Bloom', 'About A Girl', "You Know You're Right"]
7 Kaiser Chiefs ['Oh My God', 'I Predict A Riot', 'Everyday I Love You Less And Less', 'Modern Way', 'Ruby', 'Everything Is Average Nowadays', 'The Angry Mob']
7 Johan ['Tumble And Fall', 'Everybody Knows', 'Oceans', 'Day Is Done', 'Swing', "She's Got A Way With Men", "When I'm On My Own"]
7 Jimi Hendrix ['All Along The Watchtower', 'Little Wing', 'Hey Joe', 'The Wind Cries Mary', 'Crosstown Traffic', 'Purple Haze', 'Are You Experienced?']
7 Interpol ['Obstacle 1', 'Evil', 'Slow Hands', 'The Heinrich Maneuver', 'Pda', "C'Mere", 'Mammoth']
7 Eels ['Novocaine For The Soul', "Mr. E's Beautiful Blues", "Susan's House", 'Last Stop: This Town', "Hey Man Now You're Really Living", 'Your Lucky Day In Hell', 'Cancer For The Cure']
7 Editors ['Munich', 'Smokers Outside The Hospital Doors', 'An End Has A Start', 'The Racing Rats', 'All Sparks', 'Blood', 'Bullets']
7 Arctic Monkeys ['I Bet You Look Good On The Dancefloor', 'When The Sun Goes Down', 'Fake Tales Of San Francisco', 'Leave Before The Lights Come On', 'The View From The Afternoon', 'Fluorescent Adolescent', 'Teddy Picker']
6 Within Temptation ['What Have You Done', 'Ice Queen', 'Stand My Ground', 'Mother Earth', 'Running Up That Hill', 'Memories']
6 Urban Dance Squad ['Deeper Shade Of Soul', 'Demagogue', 'Fast Lane', 'Happy Go Fucked Up', 'Temporarily Expendable', 'Routine']
6 Underworld ['Born Slippy', 'Dark & Long', 'King Of Snake', 'Cowgirl', "Pearl's Girl", 'Moaner']
6 Strokes ['Last Nite', 'Someday', 'Trying Your Luck', 'You Only Live Once', 'Juicebox', 'Heart In A Cage']
6 Snow Patrol ['Run', 'Chasing Cars', 'Shut Your Eyes', 'Chocolate', 'Open Your Eyes', "You're All I Have"]
6 Prince ["Sign 'o' The Times", 'If I Was Your Girlfriend', 'When Doves Cry', "Let's Go Crazy", 'Purple Rain', 'Controversy']
6 Pixies ['Where Is My Mind', 'Debaser', 'Gigantic', 'Monkeys Gone To Heaven', 'Bone Machine', 'Motorway To Roswell']
6 Nick Cave & The Bad Seeds ['The Mercy Seat', 'Into My Arms', 'Do You Love Me?', 'As I Sat Sadly By Her Side', "Are You The One That I've Been Waiting For", 'Nature Boy']
6 Manic Street Preachers ['Motorcycle Emptiness', 'If You Tolerate This, Your Children Will Be Next', 'A Design For Life', 'Autumnsong', 'Kevin Carter', 'La Tristesse Durera']
6 Korn ['Freak On A Leash', 'Got The Life', 'Thoughtless', 'Falling Away From Me', 'A.D.I.D.A.S.', 'Twisted Transistor']
6 Killers ['Mr. Brightside', 'Somebody Told Me', 'When You Were Young', 'Read My Mind', 'Shadowplay', 'Bones']
6 Joy Division ['Love Will Tear Us Apart', "She's Lost Control", 'Transmission', 'Isolation', 'Disorder', 'Day Of The Lords']
6 Franz Ferdinand ['Take Me Out', 'Michael', 'Do You Want To', 'Matinee', 'Darts Of Pleasure', 'This FFfire']
6 Evanescence ['My Immortal', 'Lithium', 'Bring Me To Life', 'Going Under', "Call Me When You're Sober", "Everybody's Fool"]
6 Doors ['The End', 'Riders On The Storm', 'Light My Fire', 'People Are Strange', 'Break On Through', 'Love Her Madly']
6 Chemical Brothers ['Hey Boy Hey Girl', 'Galvanize', "Block Rockin' Beats", 'Believe', 'Let Forever Be', 'Do It Again']
5 Talking Heads ['Psycho Killer', 'Once In A Lifetime', 'Slippery People (Live)', 'Road To Nowhere', 'And She Was']
5 Stone Roses ['Fools Gold', 'I Wanna Be Adored', 'I Am The Resurrection', 'Made Of Stone', 'Elephant Stone']
5 Spinvis ['Bagagedrager', 'Voor Ik Vergeet', 'Smalfilm', 'Het Voordeel Van Video', 'Kindje Van God']
5 Soundgarden ['Black Hole Sun', 'Superunknown', 'Day I Tried To Live', 'Outshined', 'Burden In My Hand']
5 Rolling Stones ['Gimme Shelter', 'Sympathy For The Devil', 'Paint It Black', 'Angie', "Let's Spend The Night Together"]
5 Portishead ['Glory Box', 'Roads', 'Wandering Star', 'Sour Times', 'Numb']
5 Police ['So Lonely', 'King Of Pain', 'Roxanne', 'Message In A Bottle', 'Spirits In The Material World']
5 Nine Inch Nails ['Closer', 'The Perfect Drug', 'The Hand That Feeds', 'Starfuckers, Inc.', 'Only']
5 New Order ['Blue Monday', 'True Faith', 'Crystal', 'The Perfect Kiss', 'Bizarre Love Triangle']
5 Marilyn Manson ['The Beautiful People', 'Tourniquet', 'Disposable Teens', 'The Dope Show', "I Don't Like The Drugs"]
5 Lou Reed ['Perfect Day', 'Sweet Jane', 'Berlin', 'Walk On The Wild Side', 'Caroline Says I']
5 Led Zeppelin ['Stairway To Heaven', 'Kashmir', 'Whole Lotta Love', 'When The Levee Breaks', 'Over The Hills And Far Away']
5 Garbage ["I Think I'm Paranoid", 'Only Happy When It Rains', 'Stupid Girl', 'Queer', '#1 Crush']
5 Daft Punk ['Harder Better Faster Stronger (Alive 2007)', 'Around The World', 'Harder, Better, Faster, Stronger', 'Da Funk', 'One More Time']
5 Bush ['Glycerine', 'Everything Zen', 'Machinehead', 'The Chemicals Between Us', 'Swallowed']
5 Bob Dylan ['Like A Rolling Stone', 'Subterranean Homesick Blues', 'Lay Lady Lay', 'Rainy Day Women #12 & 35', 'Love Sick']
5 Beastie Boys ['Sabotage', 'Intergalactic', 'Fight For Your Right', 'No Sleep Till Brooklyn', 'Root Down']
5 Alanis Morissette ['Uninvited', 'Ironic', 'You Oughta Know', 'That I Would Be Good', 'Joining You']
4 Weezer ['Hash Pipe', 'Buddy Holly', 'Island In The Sun', "Say It Ain't So"]
4 Verve ['Bitter Sweet Symphony', "The Drugs Don't Work", 'Lucky Man', 'Sonnet']
4 Tori Amos ['Caught A Lite Sneeze', 'Cornflake Girl', 'Smells Like Teen Spirit', 'Spark']
4 Therapy? ['Nowhere', 'Diane', 'If It Kills Me', 'Stories']
4 Soulwax ["Much Against Everyone's Advice", 'My Cruel Joke', "Too Many DJ's", 'Any Minute Now']
4 Simple Minds ['New Gold Dream', 'Theme For Great Cities', 'Belfast Child', 'Someone Somewhere In Summertime']
4 Rage Against The Machine ['Killing In The Name Of', 'Bombtrack', 'Bulls On Parade', 'Guerilla Radio']
4 Pulp ['Common People', 'This Is Hardcore', 'Live Bed Show', 'Disco 2000']
4 Moby ["That's When I Reach For My Revolver", 'Porcelain', 'Go', 'Why Does My Heart Feel So Bad']
4 Kate Bush ['Wuthering Heights', 'Running Up That Hill', 'Army Dreamers', 'Cloudbusting']
4 K's Choice ['Not An Addict', 'Believe', 'Everything For Free', 'Mr. Freeze']
4 Jeff Buckley ['Hallelujah', 'Grace', 'Last Goodbye', 'Everybody Here Wants You']
4 Echo & The Bunnymen ['Killing Moon', 'The Cutter', 'Seven Seas', 'Bring On The Dancing Horses']
4 Deftones ['Be Quiet', 'My Own Summer', 'Change In The House Of Flies', 'Digital Bath']
4 Cult ['She Sells Sanctuary', 'Edie', 'Love Removal Machine', 'Revolution']
4 Creedence Clearwater Revival ['Fortunate Son', 'Bad Moon Rising', 'Proud Mary', 'Have You Ever Seen The Rain?']
4 Clash ['London Calling', 'Should I Stay Or Should I Go', 'The Magnificent Seven', 'Rock The Casbah']
4 Black Crowes ['Remedy', 'Hard To Handle', 'Sometimes Salvation', 'Jealous Again']
4 Bettie Serveert ['Palomine', 'Tom Boy', 'Ray Ray Rain', 'Crutches']
4 Audioslave ['Cochise', 'Like A Stone', 'Be Yourself', "Doesn't Remind Me"]
4 Arcade Fire ['Rebellion', 'Neighborhood #2', 'Keep The Car Running', 'Neighborhood #3']
4 Alice In Chains ['Would?', 'Rooster', 'Heaven Beside You', 'I Stay Away']
4 Air ['All I Need', 'Sexy Boy', 'Playground Love', 'Kelly Watch The Stars']
3 XTC ['Making Plans For Nigel', 'Senses Working Overtime', 'Dear God']
3 Who ["Baba O'Riley", "Won't Get Fooled Again", 'Pinball Wizzard']
3 Type O Negative ['Love You To Death', 'Summer Breeze', "My Girlfriend's Girlfriend"]
3 Trockener Kecks ['Met Hart En Ziel', 'Meer! Meer! Meer!', 'Niemand Thuis']
3 Tears For Fears ['Mad World', 'Sowing The Seeds Of Love', 'Everybody Wants To Rule The World']
3 Talk Talk ['Living In Another World', 'Such A Shame', "Life's What You Make It"]
3 Stone Temple Pilots ['Plush', 'Creep', 'Interstate Love Song']
3 Sonic Youth ['Diamond Sea', 'Superstar', 'Unmade Bed']
3 Soft Cell ['Say Hello, Wave Goodbye', 'Tainted Love', 'Torch']
3 Slipknot ['Wait And Bleed', 'Duality', 'Spit It Out']
3 Skunk Anansie ['Charlie Big Potato', 'Weak', 'Hedonism']
3 Sex Pistols ['Anarchy In The U.K.', 'God Save The Queen', 'Pretty Vacant']
3 Saybia ['I Surrender', 'The Day After Tomorrow', 'The Second You Sleep']
3 Ramones ['Blitzkriegbop', "Rock 'n' Roll High School", 'Beat On The Brat']
3 Raconteurs ['Steady As She Goes', 'Broken Boy Soldier', 'Hands']
3 Pogues ['A Rainy Night In Soho', 'Fiesta', 'Dark Streets Of London']
3 Patti Smith ['Dancing Barefoot', 'Because The Night', 'Frederick']
3 Offspring ['Self Esteem', "The Kids Aren't Alright", 'Come Out And Play']
3 Novastar ['The Best Is Yet To Come', 'Wrong', 'When The Lights Go Down']
3 Nick Drake ['River Man', 'Northern Sky', 'Time Has Told Me']
3 Living Colour ['Love Rears Its Ugly Head', 'Solace Of You', 'Cult Of Personality']
3 LCD Soundsystem ['North American Scum', 'Tribulations', 'Daft Punk Is Playing At My House']
3 Kraftwerk ['Autobahn', 'The Model', 'Radioactivity']
3 Kooks ['Naive', 'Ooh La', 'She Moves In Her Own Way']
3 Kinks ['Celluloid Heroes', 'You Really Got Me', 'Waterloo Sunset']
3 Johnny Cash ['San Quentin', "I'm On Fire", 'Rusty Cage']
3 Joe Jackson ['Real Men', "Steppin' Out", "It's Different For Girls"]
3 Jam ['Going Underground', "That's Entertainment", 'A Town Called Malice']
3 Infadels ["Can't Get Enough", 'Love Like Semtex', "Jagger '67"]
3 Ill Nino ['How Can I Live', 'Unreal', 'If You Still Hate Me']
3 Heather Nova ['Maybe An Angel', 'Walk This World', 'London Rain']
3 Hard-Fi ['Suburban Knights', 'Cash Machine', 'Hard To Beat']
3 Fischer Z ['So Long', 'Marliese', 'The Worker']
3 Fatboy Slim ['Rockafeller Skank', 'Right Here, Right Now', 'Praise You']
3 Fall Out Boy ["Sugar We're Going Down", 'Dance Dance', 'Thanks Fr The Mmrs']
3 Faithless ['Insomnia', 'God Is A DJ', 'Salva Mea']
3 Elvis Costello ['I Want You', "Oliver's Army", 'Alison']
3 Dandy Warhols ['Bohemian Like You', 'Every Day Should Be A Holiday', 'Not If You Were The Last Junkie On Earth']
3 DJ Shadow ['Stem/Long Stem', 'Midnight In A Perfect World', 'Six Days']
3 Cranberries ['Zombie', 'Linger', 'Ode To My Family']
3 Cracker ['Low', 'Big Dipper', 'I Hate My Generation']
3 Counting Crows ['Mr. Jones', 'Round Here', 'A Long December']
3 Cardigans ['My Favourite Game', 'Lovefool', 'Rise And Shine']
3 Bruce Springsteen ['Born To Run', 'The River', 'Streets Of Philadelphia']
3 Bloodhound Gang ['The Ballad Of Chasey Lain', 'Fire Water Burn', 'The Bad Touch']
3 Beck ['Loser', "Where It's At", "Devil's Haircut"]
3 Beach Boys ['God Only Knows', 'Good Vibrations', "Sloop John 'B'"]
3 Air Traffic ['Shooting Star', 'No More Running Away', 'Charlotte']
2 Wolfmother ['Woman', 'The Joker & The Thief']
2 Waterboys ['Whole Of The Moon', 'A Girl Called Johnny']
2 Unkle ['Rabbit In Your Headlights', 'Be There']
2 Travis ['Why Does It Always Rain On Me?', 'Sing']
2 Tom Petty & The Heartbreakers ["Mary Jane's Last Dance", "Free Fallin'"]
2 Thomas Dolby ['I Scare Myself', 'She Blinded Me With Science']
2 Thom Yorke ['Harrowdown Hill', 'The Eraser']
2 The The ['Uncertain Smile', 'This Is The Day']
2 Suzanne Vega ['Luka', 'Marlene On The Wall']
2 Supergrass ['Moving', 'Sun Hits The Sky']
2 Sugarcubes ['Birthday', 'Hit']
2 Suede ['Animal Nitrate', 'Beautiful Ones']
2 Stooges ['I Wanna Be Your Dog', '1969']
2 Stone Sour ['Bother', 'Through Glass']
2 Stereophonics ['Maybe Tomorrow', 'Dakota']
2 Starsailor ['Alcoholic', 'Poor Misguided Fool']
2 Specials ['Too Much Too Young', 'Gangsters']
2 Solo ['Mind', 'Come Back To Me']
2 Social Distortion ['I Was Wrong', 'Reach For The Sky']
2 Sisters Of Mercy ['Temple Of Love', 'This Corrosion']
2 Siouxsie & The Banshees ['Dear Prudence', 'Arabian Knights']
2 Sinead O'Connor ['Troy', 'Nothing Compares To You']
2 Silverchair ['Freak', 'Anthem For The Year 2000']
2 Razorlight ['In The Morning', 'America']
2 Racoon ['Love You More', 'Feel Like Flying']
2 Presidents Of The USA ['Lump', 'Peaches']
2 Posies ['Dream All Day', 'Please Return It']
2 Peter Gabriel ['Biko', 'Solsbury Hill']
2 Pavement ['Range Life', 'Carrot Rope']
2 Paul Weller ['You Do Something To Me', 'Wild Wood']
2 Patrick Watson ['The Great Escape', 'Luscious Life']
2 PJ Harvey ['A Perfect Day Elise', "C'mon Billy"]
2 P.O.D. ['Alive', 'Youth Of The Nation']
2 Ozzy Osbourne ['No More Tears', 'Crazy Train']
2 Osdorp Posse ['Hulp Met Eigen Gevaar', 'Geen Clubhit']
2 No Doubt ['Just A Girl', "Don't Speak"]
2 Nits ['Sketches Of Spain', 'Nescio']
2 Nina Hagen ["Auf 'em Bahnhof Zoo", 'Unbeschreiblich Weiblich']
2 Nada Surf ['Popular', 'Always Love']
2 My Chemical Romance ['Teenagers', 'Welcome To The Black Parade']
2 Morrissey ['Suedehead', 'Irish Blood, English Heart']
2 Monster Magnet ['Space Lord', 'Negasonic Teenage Warhead']
2 Moloko ['The Time Is Now', 'Sing It Back']
2 Marvin Gaye ["What's Going On", 'I Heard It Through The Grapevine']
2 Mars Volta ["L'Via L'Viaquez", 'The Widow']
2 Madrugada ['The Kids Are On High Street', 'Hands Up - I Love You']
2 Madness ['Baggy Trousers', 'One Step Beyond']
2 Limp Bizkit ['Behind Blue Eyes', 'Nookie']
2 Life Of Agony ['Lost At 22', 'Love To Let You Down']
2 Lamb ['Gorecki', 'Gabriel']
2 Kula Shaker ['Govinda', 'Hush']
2 Kings of Leon ['On Call', 'Fans']
2 Keane ['Bedshaped', 'Somewhere Only We Know']
2 Kasabian ['L.S.F.', 'Processed Beats']
2 John Lennon ['Instant Karma!', 'Working Class Hero']
2 Japan ['Nightporter', 'Adolescent Sex']
2 Jamiroquai ['Too Young To Die', 'Deeper Undeground']
2 Iron Maiden ['Run To The Hills', 'Can I Play With Madness']
2 Iggy Pop ['Lust For Life', 'The Passenger']
2 INXS ['Original Sin', 'Need You Tonight']
2 Hives ['Tick Tick Boom', 'Hate To Say I Told You So']
2 Heideroosjes ['Ik Wil Niks', 'Klapvee']
2 Guano Apes ['Open Your Eyes', 'Lords Of The Boards']
2 Grandaddy ['A.M. 180', 'The Chrystal Lake']
2 Fun Lovin' Criminals ['Scooby Snacks', "The Fun Lovin' Criminal"]
2 Flaming Lips ['Race From The Prize', "She Don't Use Jelly"]
2 Filter ['Hey Man, Nice Shot', 'Take A Picture']
2 Fear Factory ['Resurrection', 'Lynchpin']
2 Fatal Flowers ['Younger Days', 'Both Ends Burning']
2 Dropkick Murphys ['The Good Rats', 'The Wild Rover']
2 Dinosaur Jr ['Freak Scene', "I Don't Think So"]
2 Deep Purple ['Child In Time', 'Smoke On The Water']
2 Dead Kennedys ['California Uber Alles', 'Too Drunk To Fuck']
2 Daryll-Ann ['We Love Danger', 'Surely Justice']
2 Damien Rice ['9 Crimes', 'Cannonball']
2 Cypress Hill ['Insane In The Brain', 'Rock Superstar']
2 Creed ['With Arms Wide Open', "What's This Life For"]
2 Coparck ['A Good Year For The Robots', 'The World Of Tomorrow']
2 Caesar ['Before My Head Explodes', 'Situations Complications']
2 CSS ["Let's Make Love And Listen To Death From Above", 'Off The Hook']
2 Buffalo Tom ['Taillights Fade', "I'm Allowed"]
2 Bran Van 3000 ['Drinking In L.A.', 'Astounded']
2 Bob Marley & The Wailers ['Redemption Song', 'Get Up, Stand Up']
2 Blink 182 ['All The Small Things', "What's My Age Again?"]
2 Billy Idol ['White Wedding', 'Eyes Without A Face']
2 Belle & Sebastian ["She's Losing It", 'Funny Little Frog']
2 Band of Horses ['The Funeral', 'Is There A Ghost']
2 Bad Religion ['Punk Rock Song', 'Infected']
2 B 52's ['Love Shack', 'Rock Lobster']
2 At The Drive In ['One Armed Scissor', 'Invalid Litter Dept.']
2 Anne Clark ['Our Darkness', 'Self Destruct']
2 Amy Winehouse ['Rehab', "You Know I'm No Good"]
2 Afghan Whigs ['Gentlemen', 'Debonair']
2 AC/DC ['Whole Lotta Rosie', 'Thunderstruck']
2 A Perfect Circle ['Judith', '3 Libras']
2 A Flock Of Seagulls ['I Ran', 'Wishing I Had A Photograph']
2 30 Seconds To Mars ['From Yesterday', 'The Kill (Bury Me)']
2 3 Doors Down ['Kryptonite', 'Here Without You']
1 Zutons ['Valerie']
1 Zoot Woman ['Living In A Magazine']
1 Zita Swoon ['Maria']
1 ZZZ ['Ecstacy']
1 Young Gods ['Lucidogen']
1 Yellowcard ['Way Away']
1 World Party ['Ship Of Fools']
1 Wombats ["Let's Dance To Joy Division"]
1 Wir Sind Helden ['Von Hier An Blind']
1 Wipers ['Over The Edge']
1 Von Bondies ["C'mon C'mon"]
1 Voicst ['Whatever You Want From Life']
1 Visage ['Fade To Grey']
1 View ['Same Jeans']
1 Verve Pipe ['The Freshmen']
1 Veils ['Advice For Young Mothers To Be']
1 Undertones ['Teenage Kicks']
1 Ultravox ['Vienna']
1 Ugly Kid Joe ['Everything About You']
1 U2 & Green Day ['The Saints Are Coming']
1 Tubeway Army ['Are Friends Electric']
1 Tracy Chapman ['Fast Car']
1 Toy Dolls ['Nellie The Elephant']
1 Tonic ['If You Could Only See']
1 Tindersticks ft. Isabella Rosselini ['A Marriage Made In Heaven']
1 Tiger Army ['Forever Fades Away']
1 Tiamat ['Vote For Love']
1 This Mortal Coil ['Song To The Siren']
1 Thin Lizzy ['Whiskey In The Jar']
1 Tenacious D ['Tribute']
1 Temple Of The Dog ['Hunger Strike']
1 TV On The Radio ['Staring At The Sun']
1 Sum 41 ['Fat Lip']
1 Suicidal Tendencies ['Institutionalized']
1 Sublime ['What I Got']
1 Style Council ['Shout To The Top']
1 Stranglers ['Golden Brown']
1 Stiltskin ['Inside']
1 Stereo MC's ['Connected']
1 Staind ["It's Been A While"]
1 Spineshank ['New Disease']
1 Spin Doctors ["Little Miss Can't Be Wrong"]
1 Spider Murphy Gang ['Skandal Im Sperrbezirk']
1 Smash Mouth ['All Star']
1 Simple Plan ['Welcome To My Life']
1 Sigur Ros ['Svefn-G-Englar']
1 Sid Vicious ['My Way']
1 Shriekback ['Lined Up']
1 Shirts ['Laugh And Walk Away']
1 Shins ['Phantom Limb']
1 Sepultura ['Roots Bloody Roots']
1 Sebadoh ['Careful']
1 Screaming Trees ['Nearly Lost You']
1 Scissor Sisters ["I Don't Feel Like Dancing"]
1 Scene ['Iedereen Is Van De Wereld']
1 Ryan Adams ['New York, New York']
1 Rufus Wainwright ['Going To A Town']
1 Royksopp/Erlend Oye ['Eple']
1 Royksopp ['Poor Leno']
1 Roxy Music ['Both Ends Burning']
1 Roots ['The Seed']
1 Rollins Band ['Liar']
1 Rifles ['Peace & Quiet']
1 Rialto ['Monday Morning']
1 Rancid ['Time Bomb']
1 Radio 4 ['Enemies Like This']
1 Public Enemy ["Don't Believe The Hype"]
1 Propaganda ['Duel']
1 Primal Scream & Kate Moss ['Some Velvet Morning']
1 Postal Service ['Such Great Heights']
1 Porno For Pyros ['Pets']
1 Placebo & David Bowie ["Without You I'm Nothing"]
1 Phoenix ['If I Ever Feel Better']
1 Peter, Bjorn & John ['Young Folks']
1 Pet Shop Boys ['West End Girls']
1 Pennywise ['Brohymn']
1 Paradise Lost ['Say Just Words']
1 Papa Roach ['Last Resort']
1 Panic At The Disco ['I Write Sins Not Tragedies']
1 PIL ['This Is Not A Lovesong']
1 Ozark Henry ['Sweet Instigator']
1 Orchestral Manoeuvres In The Dark ['Maid Of Orleans']
1 Orb ['Little Fluffy Clouds']
1 Nightwish ['Amaranth']
1 Nickelback ['How You Remind Me']
1 Nick Cave & PJ Harvey ['Henry Lee']
1 Nick Cave & Kylie Minogue ['Where The Wild Roses Grow']
1 Newton Faulkner ['Dream Catch Me']
1 New Musik ['This World Of Water']
1 Nathalie Merchant ['Carnival']
1 NOFX ['Leave It Alone']
1 N.E.R.D. ['Lapdance']
1 My Morning Jacket ['Off The Record']
1 Motorpsycho ['Hey Jane']
1 Motorhead ['Ace Of Spades']
1 Moke ['Last Chance']
1 Modest Mouse ['Float On']
1 Ministry ['Jesus Built My Hotrod']
1 Millionaire ['Ballad Of Pure Thought']
1 Midnight Oil ['Beds Are Burning']
1 Mew ["The Zookeeper's Boy"]
1 Metallica ft. Marianne Faithfull ['The Memory Remains']
1 Mercury Rev ['Goddess On A Highway']
1 Melissa Etheridge ['Like The Way I Do']
1 Mekon ['Please Stay (Royksopp Remix)']
1 Mark Ronson ['Valerie']
1 Marc Almond ['Tears Run Rings']
1 Manu Chao ['Me Gustas Tu']
1 Mansun ['Legacy']
1 Mano Negra ['King Kong Five']
1 Make Good Your Escape ['Real']
1 Magic Numbers ['Forever Lost']
1 Mad Season ['Wake Up']
1 MC 900Ft Jesus ['The City Sleeps']
1 M83 ["Don't Save Us From The Flames"]
1 M.I.A. ['Bucky Done Gun']
1 Lush ['Ladykillers']
1 Lotus Eaters ["You Don't Need Someone New"]
1 Lostprophets ['Last Train Home']
1 Lloyd Cole ['Rattlesnakes']
1 Lifehouse ['Hanging By A Moment']
1 Libertines ["Can't Stand Me Now"]
1 Lenny Kravitz ['Are You Gonna Go My Way?']
1 Lemonheads ["It's A Shame About Ray"]
1 Laurie Anderson ['O Superman']
1 La's ['There She Goes']
1 Kristin Hersh & Michael Stipe ['Your Ghost']
1 Krezip ['I Would Stay']
1 Klaxons ['Golden Skans']
1 Kings Of Leon ['Red Morning Light']
1 Killing Joke ['Love Like Blood']
1 Kent ['If You Were Here']
1 Keith Caputo ['Selfish']
1 Ke ['Strange World']
1 KLF ['Last Train To Transcentral']
1 Justice ['D.A.N.C.E.']
1 Junkie XL ['Saturday Teenage Kick']
1 John Frusciante ['Going Inside']
1 John Cougar Mellencamp ['Jack & Diane']
1 John Cale ["Fear Is A Man's Best Friend"]
1 Jimmy Eat World ['Big Casino']
1 Jesus & Mary Chain ['Just Like Honey']
1 Jayhawks ['Take Me With You']
1 Jars Of Clay ['Flood']
1 Janis Joplin ['Me And Bobby Mcgee']
1 Jane's Addiction ['Been Caught Stealing']
1 James ['Born Of Frustration']
1 Jack Johnson ['Sitting, Waiting, Wishing']
1 Ignite ['Veteran']
1 Iggy Pop & Kate Pierson ['Candy']
1 Ian Brown ['F.E.A.R.']
1 Human League ['The Lebanon']
1 House Of Pain ['Jump Around']
1 Hot Chip ['Ready For The Floor']
1 Hoobastank ['The Reason']
1 Hole ['Violet']
1 High Fidelity ['Scream If You Want To Go Faster']
1 Herman Brood And His Wild Romance ['Saturday Night']
1 Hawkwind ['Silver Machine']
1 Happy Mondays ['Step On']
1 HIM ['Join Me']
1 Gun Club ['Sex Beat']
1 Guillemots ['Trains To Brazil']
1 Grauzone ['Eisbar']
1 Grace Jones ['Slave To The Rhythm']
1 Gorki ['Mijn Dierbare Vijand']
1 Gorillaz ft. Shaun Ryder ['Dare']
1 Gorillaz ft. De La Soul ['Feel Good Inc.']
1 Gorillaz ['Clint Eastwood']
1 Good, The Bad & The Queen ['Herculean']
1 Good Charlotte ['Dance Floor Anthem']
1 Goo Goo Dolls ['Iris']
1 God Machine ['Home']
1 Gavin Friday ['I Want To Live']
1 Gathering ['Strange Machines']
1 Gary Numan ['Cars']
1 Gangstarr ['Lovesick']
1 Fugazi ['Blueprint']
1 Freur ['Doot Doot']
1 Fratellis ['Chelsea Dagger']
1 Frank Zappa ["Dancin' Fool"]
1 Frank Black ['Hang On To Your Ego']
1 Fountains Of Wayne ['Sink To The Bottom']
1 Flash & The Pan ['Hey St. Peter']
1 Fischerspooner ['Emerge']
1 Fictionplane ['Two Sisters']
1 Feeling ['Sewn']
1 Fastball ['The Way']
1 Falco ['Jeanny']
1 Faint ['Agenda Suicide']
1 Fad Gadget ['Collapsing New People']
1 Face Tomorrow ['My World Within']
1 Extince ['Spraakwater']
1 Everything But The Girl ['Missing (Todd Terry Remix)']
1 Everlast ["What It's Like"]
1 Elliott Smith ['Waltz #2']
1 Electric Six ['Gay Bar']
1 Elastica ['Stutter']
1 Eddie Vedder ['Hard Sun']
1 Eagles Of Death Metal ['I Want You So Hard']
1 Dredg ['Bug Eyes']
1 Dodgy ['In A Room']
1 Disturbed ['Down With The Sickness']
1 Department S ['Is Vic There']
1 Delain ['Frozen']
1 Death In Vegas ft. Iggy Pop ['Aisha']
1 Death Cab For Cutie ['Soul Meets Body']
1 Dears ['Lost In The Plot']
1 Dead 60s ['Riot Radio']
1 Deacon Blue ['Your Town']
1 Dave Clarke ft. Chicks On Speed ['What Was Her Name?']
1 Danko Jones ['Lovercall']
1 Damned ['New Rose']
1 DC Talk ['Jesus Freak']
1 Curtis Mayfield ['Superfly']
1 Crowded House ["Don't Dream It's Over"]
1 Crash Test Dummies ['Mmm, Mmm, Mmm, Mmm']
1 Cornershop ['Brimful Of Asha (Fatboy Slim Remix)']
1 Cold War Kids ['Hang Me Up To Dry']
1 Claw Boys Claw ['Rosie']
1 Clap Your Hands Say Yeah ['In This Home On Ice']
1 Cinematics ['Break']
1 Church ['Under The Milky Way']
1 Chris Isaak ['Wicked Game']
1 Chris Cornell ["Can't Change Me"]
1 Charlatans ['Only One I Know']
1 Calling ['Wherever You Will Go']
1 Cake ['The Distance']
1 Buzzcocks ['Ever Fallen In Love?']
1 Butthole Surfers ['Pepper']
1 Buggles ['Lenny']
1 Bronski Beat ['Smalltown Boy']
1 Breeders ['Cannonball']
1 Brad ['The Day Brings']
1 Bowling For Soup ['1985']
1 Bomfunk MC's ['Freestyler']
1 Boards Of Canada ['1969']
1 Blue Nile ['Tinseltown In The Rain']
1 Blondie ['Hanging On The Telephone']
1 Blind Melon ['No Rain']
1 Black Sabbath ['Paranoid']
1 Black Rebel Motorcycle Club ["Whatever Happened To My Rock 'n' Roll"]
1 Black Flag ['TV Party']
1 Billy Bremner ['Loud Music In Cars']
1 Beth Hart ['L.A. Song']
1 Beloved ['Sweet Harmony']
1 Bauer ['Dunce']
1 Basement Jaxx ['Good Luck']
1 Bap ['Kristallnaach']
1 Babylon Zoo ['Spaceman']
1 Automatic ['Monster']
1 Audio Bullys ["We Don't Care"]
1 Atari's ['The Boys Of Summer']
1 Aphex Twin ['Windowlicker']
1 And You Will Know Us By The Trail Of Dead ['Another Morning Stoner']
1 Amy MacDonald ['This is the Life']
1 Alphaville ['Forever Young']
1 Alien Ant Farm ['Smooth Criminal']
1 Aggrolites ['Mr. Misery']
1 Adam Ant ['Stand and Deliver']
1 AFI ['Miss Murder']
1 A Tribe Called Quest ['I Left My Wallet In El Segundo']
1 3 Colours Red ['Beautiful Day']
1 16 Horsepower ['Black Soul Choir']

Volgende: Using exceptions in Java 10-'08 Using exceptions in Java
Volgende: Dr. Obvious to the rescue 10-'08 Dr. Obvious to the rescue

Comments


By Tweakers user Thyraon, Saturday 11 October 2008 14:48

Nice example of expressive scripting, these things make me love Ruby - my favorite language - where it's possible to do things like this in the same manner without the boilerplate you see in other (scripting) languages.

By Tweakers user Haan, Saturday 11 October 2008 15:29

Just for curiosity, how would this script look like in javascript for example? I'm not familiar with Python, so I don't see the beauty of the script ;)

By Tweakers user merlijn85, Saturday 11 October 2008 20:22

Here's a snippet of code that does the same thing in perl:


code:
1
2
3
4
5
6
7
8
9
10
my $db;
while ( <> ) {
  if ( m/^\d+\. (.+?) - (.+)$/gi ) {
    push @{$db->{$1}}, $2;
  }
}

foreach (sort { @{$db->{$b}} <=> @{$db->{$a}} } keys %{$db}) {
  print @{$db->{$_}} . " $_ [ @{$db->{$_}} ]\n";
}


It expects the first argument to be the name of the file holding the songs list. There is pros and cons to both versions. The perl code is shorter, but probably harder to comprehend for users not familiar with perl. What you should notice is that there is different standard behavior in both languages. In perl there is no need to initialize the array for songs, while we do need to specify that we want this type of sorting (descending by array size). Also you need a little more work to print it all tidily in perl.

However we can now hack on this a little more, and turn it into a one-liner:

code:
1
perl -e 'while ( <> ) { push (@{$db->{$1}}, $2) if (m/^\d+\. (.+?) - (.+)$/gi); } print @{$db->{$_}} . " $_ [ @{$db->{$_}} ]\n" foreach (sort { @{$db->{$b}} <=> @{$db->{$a}} } keys %{$db});' kink.txt


Notice kink.txt has the songlist.

By Tweakers user Confusion, Saturday 11 October 2008 22:12

@merlijn85:
I think "probably harder to comprehend" is quite an understatement ;).

While I appreciate the art of writing one-liners, I want to stress that conciseness was not a goal. Otherwise I would have written something like:

Python:
1
2
3
4
5
6
7
8
import re

ar = {}
for g in [re.search("\d+\. (.+?) - (.+)", l).groups() for l in open("songs")]:
    ar[g[0]] = [g[1]] if not g[0] in ar else ar[g[0]] + [g[1]]

for (l, a) in sorted([(len(s), a) for (a, s) in ar.items()], reverse=True):
    print l, a, ar[a]

which I think is already quite incomprehensible.

[Comment edited on Saturday 11 October 2008 22:46]


By Tweakers user Elijan9, Monday 13 October 2008 09:50

You are forgetting to close the file handler. Better is to use:

Python:
1
2
for line in open("songs"):
    ...


Or with the "with_statement" :

Python:
1
2
3
4
5
# Next line needed for Python2.5 (official 2.6/3.0 feature
from __future__ import with_statement

with open("songs") as songs:
    ...


That way, the file descriptor will be automatically closed when it is no longer needed. Otherwise the file descriptor will not be closed until terminating (AFAIK).
And the code will be a bit faster when using re.compile(..) to compile the regular expression only once instead of at every iteration.

By fire, Friday 24 October 2008 22:55

it's imho easier and more readable to use the setdefault() method of an dict:

In [1]: a = {}
In [2]: a.setdefault('artist', []).append('song a')
In [3]: a.setdefault('artist', []).append('song b')
In [4]: a
Out[4]: {'artist': ['song a', 'song b']}

By Thomas, Saturday 25 October 2008 01:58

Ruby, requires 1.9, or 1.8 with Oniguruma patch for the named regexp groups:


code:
1
2
3
4
5
6
7
8
9
artists = Hash.new {|h,k| h[k] = [] } # set default value; the closure is called on each missing key
File.foreach("songs") do |line|
  next unless match = /\d+\. (?<artist>.+?) - (?<song>.+)/.match(line)
  artists[match[:artist]] << match[:song]
end

artists.sort_by {|_, songs| songs.size }.reverse.each do |artist, songs|
  puts "#{songs.size} #{artist} #{songs.inspect}"
end


You can do similar with Python, ala:


code:
1
2
matcher = re.search("\d+\. (?P<artist>.+?) - (?P<song>.+)", line)
artists.setdefault(matcher.group('artist'), []).append(matcher.group('song'))


Might be nicer than using numeric groups and making new variables to name them afterwards.

By Casey, Saturday 25 October 2008 03:41

The line: "if not artist in artists:" could also be written "if artist not in artists:" It's a very simple thing but makes readability so much better.

By Marius Gedminas, Saturday 25 October 2008 04:19

The original script is quite good already.

Since everyone is posting their own versions, here's mine:


code:
1
2
3
4
5
6
7
8
9
10
11
12
import re
from collections import defaultdict

artists = defaultdict(list)
for line in file("songs"):
    artist, song = re.search("\d+\. (.+?) - (.+)", line).groups()
    artists[artist].append(song)

artists = [(len(songs), artist, songs) for (artist, songs) in artists.items()]
artists.sort(reverse=True)
for count, artist, songs in artists:
    print count, artist, songs

By Tweakers user Confusion, Monday 27 October 2008 17:28

Thank you for your suggestions. I was unaware of the possibility of using named regex groups, which is indeed very convenient. I also wasn't aware of the defaultdict, which I think is more readable than the setdefault() solution.

Comments are closed