Advertisement
abdullyahuza

reading-text-files

May 25th, 2022
570
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # Read text from a file, and count the occurence of words in that text
  2. # Example:
  3. # count_words("The cake is done. It is a big cake!")
  4. # --> {'The': 1, 'cake': 1, 'is': 2, 'done.': 1, 'It': 1, 'a': 1, 'big': 1, 'cake!': 1}
  5.  
  6. def read_file_content(filename):
  7.     # [assignment] Add your code here
  8.     with open(filename, 'r') as file:
  9.         content = file.read()    
  10.     return content
  11.  
  12.  
  13. def count_words():
  14.     text = read_file_content("./story.txt")
  15.     # [assignment] Add your code here
  16.  
  17.     # dict to hold key/value of word/number of occurrence
  18.     words_count = {}
  19.  
  20.     # convert the string into a list
  21.     text_to_list = text.split() #list
  22.     # return {"as": 10, "would": 20}
  23.     for word in text_to_list:
  24.         words_count[word] = text_to_list.count(word)
  25.  
  26.     return words_count
  27.  
  28. words_count = count_words()
  29. print(words_count)
Advertisement
RAW Paste Data Copied
Advertisement