Thursday, November 30, 2023

Count words in a file in Python program

 with open ('E:\\source_files\\file1.txt','r') as file:

    #Read the entire file
content = file.read()
print(content)

#C:\bigdata\anaconda3\envs\py38\python.exe C:\bigdata\PycharmProjects\Test_Project\test1.py

#Bangalore is Karnataka
#Chennai is Tamilnadu

#split the content into words
words = content.split()
print(f'output after split is :{words}')
# output after split is :['Bangalore', 'is', 'Karnataka', 'Chennai', 'is', 'Tamilnadu']

#count the number of words:
word_count = len(words)
print(f'final output count is :{word_count}')
#final output count is :6

No comments:

Post a Comment