7367network

Word Counter

Nov 22nd, 2021
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. # normalize
  2. # -----
  3. # This function takes a word and returns the same word
  4. # with:
  5. # - All non-letters removed
  6. # - All letters converted to lowercase
  7. def normalize(word):
  8. return "".join(letter for letter in word if letter.isalpha()).lower()
  9.  
  10. # get_counts
  11. # -----
  12. # This function takes a filename and generates a dictionary
  13. # whose keys are the unique words in the file and whose
  14. # values are the counts for those words.
  15. def get_counts(filename):
  16. result_dict = {}
  17. file = open(filename)
  18. for line in file:
  19. result_dict["_total"] = len(line.split())
  20. for word in line.strip().split():
  21. if word == " ":
  22. continue
  23. else:
  24. word = normalize(word)
  25. if word in result_dict:
  26. result_dict[word] += 1
  27. else:
  28. result_dict[word] = 1
  29. return result_dict
  30. print("Word count: " + len(result_dict))
  31. print("Total word count: " + word_count)
  32. # Get the counts for the two shortened versions
  33. # of the texts
  34. shakespeare_counts = get_counts("hamlet.txt")
  35. austen_counts = get_counts("pride_and_prejudice.txt")
  36.  
  37. # Check the contents of the dictionaries
  38. for key in shakespeare_counts:
  39. print(key + ": " + str(shakespeare_counts[key]))
  40.  
  41. print("-----")
  42.  
  43. for key in austen_counts:
  44. print(key + ": " + str(austen_counts[key]))
Advertisement
Add Comment
Please, Sign In to add comment