Geen omschrijving

word_count.py 580B

1234567891011121314151617
  1. def count_words(filename):
  2. """Count the approximate number of words in a file."""
  3. try:
  4. with open(filename, encoding='utf-8') as f_obj:
  5. contents = f_obj.read()
  6. except FileNotFoundError:
  7. pass
  8. else:
  9. # Count approximate number of words in the file.
  10. words = contents.split()
  11. num_words = len(words)
  12. print("The file " + filename + " has about " + str(num_words) + " words.")
  13. filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
  14. for filename in filenames:
  15. count_words(filename)