Guest User

Exercice Sam & Max

a guest
Dec 16th, 2013
276
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.84 KB | None | 0 0
  1. # encoding: utf-8
  2. from __future__ import unicode_literals, absolute_import, print_function
  3.  
  4. import sys
  5. import re
  6. import unicodedata
  7. from collections import defaultdict
  8.  
  9. from pprint import pprint
  10.  
  11. def main():
  12.  
  13.     with open(sys.argv[1]) as f:
  14.         text = f.read().decode('utf-8').lower()
  15.  
  16.     re_punctuation = re.compile('[^a-z0-9]')
  17.  
  18.     text = ''.join(c for c in unicodedata.normalize('NFD', text)
  19.                   if unicodedata.category(c) != 'Mn')
  20.     text = text.replace("œ", "oe")
  21.     text = re_punctuation.sub(' ', text).strip()
  22.  
  23.     words = re.split(r' +', text)
  24.  
  25.     df = defaultdict(list)
  26.     for pos, word in enumerate(words):
  27.         df[word].append(pos)
  28.  
  29.     df = sorted(df.items(), key = lambda (word,positions):(len(positions), sorted(positions)))
  30.  
  31.     pprint(df)
  32.  
  33.  
  34. if __name__ == "__main__":
  35.     main()
Advertisement
Add Comment
Please, Sign In to add comment