lamiastella

sort

May 31st, 2016
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.06 KB | None | 0 0
  1. """
  2. for line in file:
  3.    print line
  4. """
  5. def word_map(string):
  6.     word_dict = {}
  7.     for word in string.split():
  8.         word = filter(str.isalnum, word).lower()
  9.         word = word.strip()
  10.         if word != '':
  11.             if word in word_dict.keys():
  12.                 word_dict[word] +=1
  13.             else:
  14.                 word_dict[word] = 1
  15.     return word_dict
  16. """
  17. my_dict= word_map("This is a string , this is another string too")
  18. for k in my_dict:
  19.    print k, my_dict[k]
  20. """
  21. file = open("story.txt", "r")
  22. file_string = file.read()
  23.  
  24. words = word_map(file_string)
  25. popular_words = sorted(words, key=words.get, reverse=True)
  26. for k in popular_words:
  27.     print k, popular_words[k]
  28.  
  29.  
  30. /Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/mona/PycharmProjects/PythonCodes/top_words.py
  31. the
  32. Traceback (most recent call last):
  33.   File "/Users/mona/PycharmProjects/PythonCodes/top_words.py", line 27, in <module>
  34.     print k, popular_words[k]
  35. TypeError: list indices must be integers, not str
  36.  
  37. Process finished with exit code 1
Add Comment
Please, Sign In to add comment