Saturday, July 11, 2020

Python Text File Program Solution from Sumita Arora Book


Count characters, words and lines present in a text file using python program


Note : text file and python program must present in same foloder

Count words in a file
f=open('abc.txt')
c=0
s=f.read()  # read file and store the content of file in a string s
w=s.split() # split the contents of s and store it into list w 
for i in w:
    c=c+1
print(c)
f.close()

Count ‘india’ word from file

f=open('abc.txt')
c=0
s=f.read()
w=s.split()
for i in w:
    if(i=="india"):
        c=c+1
print(c)
f.close()

Count  and print words having length <=3  from file

f=open('abc.txt')
c=0
s=f.read()
w=s.split()
for i in w:
    if(len(i)<=3):  #match the length of item in list
        print(i)
        c=c+1
print(c)


Count lines in a file
f=open('abc.txt')
c=0
list=f.readlines() # Read lines from file and store in a list named list
for i in list:
    c=c+1
print(c)
f.close()

Count lines starts from ‘s’ 

f=open('abc.txt')
c=0
list=f.readlines()
for i in list:
    if(i[0]=='s'): # match each item of list starts with s or not
        c=c+1
print(c)
f.close()

Count characters from file
f=open('abc.txt')
count=0
s=f.read()
w=s.split()
for i in w:      # traverse every item in list
    for c in i:  # traverse every character in item
        count=count+1
print(count)



Count lower case alphabets from file

f=open('abc.txt')
count=0
s=f.read()
w=s.split()
for i in w:
    for c in i:
        if(i.islower()): # find the given character is lower case or not
            count=count+1

print(count)


Count number of  digits present in text file

f=open('abc.txt')
count=0
s=f.read()
w=s.split()
for i in w:
    for c in i:
        if(i.isdigit()): # find the given character is digit or not
            count=count+1


print(count)

Print first and last line of text file
f=open('abc.txt')
lines=f.readlines()
print(lines[-1])   # -1 is the index of last item in a list
print(lines[0])    # 0 in the index of first item in a list


Print longest line from  a text file

f=open('abc.txt')
c=0
list=f.readlines()
longest=""
for i in list:
    if(len(i)>len(longest)): 
        longest=i
print(longest)

Program to display size of a file in bytes

f=open('abc.txt')
s=f.read()  # read file and store the content of file in a string s
size=len(s)
print("size in bytes:",size)


No comments:

Post a Comment