This example tell you how to read text file content and get the words count in the text file in python. This example is created with eclipse PyDev plugin, you can read article in reference section to learn more about PyDev.
1. Python Get Text File Words Count Project Creation Steps.
- Open Eclipse PyDev.
- Click File —> New —> Others menu item, then select PyDev Package to create a package com.dev2qa.example.file.
- Click File —> New —> Others menu item, then select PyDev Module to create a module file GetTextFileWordsCount.py.
- Copy below source code into it.
- Right click the source code, click Run As —> Python Run menu item to run the example.
- Below is the project file package explorer panel.
''' Created on Aug 18, 2018 @author: zhaosong ''' # This function will read words count in a text file. def count_words_in_text_file(file_path): ret = -1 try: # Open the text file. file_object = open(file_path, "r") # Get all file content in a string. file_content = file_object.read() # Split the file content into an array. words_array = file_content.split() # Get words array length. words_array_len = len(words_array) ret = words_array_len print(file_path + " contains " + str(words_array_len) + " words.") except FileNotFoundError: print(file_path + " do not exist. ") except PermissionError: print("You do not have permission to read file " + file_path) except IOError: print("IOError.") return ret if __name__ == '__main__': count_words_in_text_file("./GetTextFileWordsCount.py")
(Visited 282 times, 2 visits today)