Counting Character with Python
Simple Python coding tutorial for beginners
In our last article, we challenged ourselves to improve our word counter program by adding a character count feature. If you missed the last post, you can find it here:
Solution
We introduce the count_characters
function, dedicated to counting characters in a file:
def count_characters(file_path: str) -> int:
"""Count characters in a file.
:param file_path: The path to the file to count characters for.
:return: The number of characters in the file.
"""
with open(file_path, "r") as file:
contents = file.read()
return len(contents)
This function opens the file, reads its contents, and returns the total character count.
Full Code
We’ve integrated this new function into our existing word counter script:
"""Text analysis."""
import argparse
def count_words(file_path: str) -> int:
"""Count words in a file.
:param file_path: The path to the file to count words for.
:return: The number of words in the file.
"""
with open(file_path, "r") as file:
contents = file.read()
words = contents.split()
return len(words)
def count_characters(file_path: str) -> int:
"""Count characters in a file.
:param file_path: The path to the file to count characters for.
:return: The number of characters in the file.
"""
with open(file_path, "r") as file:
contents = file.read()
return len(contents)
def main(file_path: str) -> None:
"""Word and character counter main function.
:param file_path: The path to the file to count words and characters for.
"""
word_count = count_words(file_path)
character_count = count_characters(file_path)
print(f"The file contains {word_count} words and {character_count} characters.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Word and Character Counter")
parser.add_argument("file_path", type=str, help="Path to the text file")
args = parser.parse_args()
main(args.file_path)
This improved script now outputs both word and character counts, providing a more comprehensive text file analysis.
Testing the Program
To test the updated script, run the following command:
$ python easy/text_analysis.py example.txt
The file contains 4 words and 18 characters
Further Reading
If you want to learn more about programming and, specifically, Python and Java, see the following course:
Note: If you use my links to order, I’ll get a small kickback. So, if you’re inclined to order anything, feel free to click above.