Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # normalize
- # -----
- # This function takes a word and returns the same word
- # with:
- # - All non-letters removed
- # - All letters converted to lowercase
- def normalize(word):
- return "".join(letter for letter in word if letter.isalpha()).lower()
- # get_counts
- # -----
- # This function takes a filename and generates a dictionary
- # whose keys are the unique words in the file and whose
- # values are the counts for those words.
- def get_counts(filename):
- result_dict = {}
- file = open(filename)
- for line in file:
- result_dict["_total"] = len(line.split())
- for word in line.strip().split():
- if word == " ":
- continue
- else:
- word = normalize(word)
- if word in result_dict:
- result_dict[word] += 1
- else:
- result_dict[word] = 1
- return result_dict
- print("Word count: " + len(result_dict))
- print("Total word count: " + word_count)
- # Get the counts for the two shortened versions
- # of the texts
- shakespeare_counts = get_counts("hamlet.txt")
- austen_counts = get_counts("pride_and_prejudice.txt")
- # Check the contents of the dictionaries
- for key in shakespeare_counts:
- print(key + ": " + str(shakespeare_counts[key]))
- print("-----")
- for key in austen_counts:
- print(key + ": " + str(austen_counts[key]))
Advertisement
Add Comment
Please, Sign In to add comment