In this python file program, we will count the total number of special characters in a file with the help of the below-given steps. Let’s consider we have readcontent.txt file with the below content.
#readcontent.txt
Line1 : This is @ndia.
Line2 : This is $America.
Line3 : This is Canada?.
Line4 : This is #Australia.
Steps to solve the program
- Open the first file by using open(“readcontent.txt”).
- Read the data and split it into words using file.read().split().
- Create a count variable and assign its value equal to 0.
- Create a list of special characters
- Use a for loop to iterate over the words.
- Use a nested for loop to iterate over the characters in the word.
- If the character is in the list then add 1 to the count variable.
- Print the output.
# Open the file
file = open('readcontent.txt')
# Read data and converting it into words
words = file.read().split()
# Create count variable
count = 0
# Create list of special characters
special = ['!','@','#','$','%','^','&','*',
'~','`','?',':',';']
# Iterate over words
for word in words:
# Iterate over characters in the word
for char in word:
# Check for special characters
if char in special:
# Add 1 to the count variable for each special character
count += 1
# Print output
print("Total number of digits in the file: ",count)
Output :
Total number of digits in the file: 8