Python Count Words In Text File Example

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.

  1. Open Eclipse PyDev.
  2. Click File —> New —> Others menu item, then select PyDev Package to create a package com.dev2qa.example.file.
  3. Click File —> New —> Others menu item, then select PyDev Module to create a module file GetTextFileWordsCount.py.
  4. Copy below source code into it.
  5. Right click the source code, click Run As —> Python Run menu item to run the example.
  6. Below is the project file package explorer panel.
    get text file words count in python example
'''
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")

 

READ :   How To Make A Website With Python And Django

Reference

  1. How To Run Python In Eclipse With PyDev
(Visited 120 times, 1 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.