code_junkie

Translating Python Regexp to Shell

Nov 14th, 2011
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. # script to get all of the genres from itunes
  4.  
  5. import re,sys,sets
  6.  
  7.  
  8. ## Boosted from the internet to handle HTML entities in Genre names
  9. def unescape(text):
  10. def fixup(m):
  11. text = m.group(0)
  12. if text[:2] == "&#":
  13. # character reference
  14. try:
  15. if text[:3] == "&#x":
  16. return unichr(int(text[3:-1], 16))
  17. else:
  18. return unichr(int(text[2:-1]))
  19. except ValueError:
  20. pass
  21. else:
  22. # named entity
  23. try:
  24. text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
  25. except KeyError:
  26. pass
  27. return text # leave as is
  28. return re.sub("&#?w+;", fixup, text)
  29.  
  30.  
  31. # probably faster to use a regex than to try to walk
  32. # the entire xml document and aggregate the genres
  33. try:
  34. xml_path = "/Users/%s/Music/iTunes/iTunes Music Library.xml" % sys.argv[1]
  35. except:
  36. print 'tUsage: python '+sys.argv[0]+' <your OSX username>'
  37. raise SystemExit
  38.  
  39. pattern = "<key>Genre</key><string>([^<]+)</string>"
  40.  
  41. try:
  42. xml = file(xml_path,'r').read()
  43. except:
  44. print 'tUnable to load your iTunes Library XML file'
  45. raise SystemExit
  46.  
  47. matches = re.findall(pattern,xml)
  48. uniques = map(unescape,list(sets.Set(matches)))
  49. ## need to write these out somewhere so the applescript can read them
  50. sys.stdout.write('|'.join(uniques))
  51. raise SystemExit
  52.  
  53. tell application "iTunes" to get genre of every track of library playlist 1
Add Comment
Please, Sign In to add comment