Ques . WAP to count frequency of characters in a given file.Can u use character frequency to test whether the given file is Python program file, C program file or a text file
Answer :
Program -1
f="C:\\Users\\HP\\Desktop\\g.txt"
file = open ( f, "r" )
a=[]
b={}
for i in file:
for j in range(0,len(i)):
a.append(i[j])
for i in a:
if i in b:
b[i]+=1
else:
b[i]=1
print(b)
c=f.split(".")
if c[1]=="txt":
print("\n\nit is a text file")
elif c[1]=="cpp":
print("\n\nit is a c++ file")
else:
print("\n\nit is a c file")
Output 1 :
{'g': 2, 'o': 7, 'e': 12, 'd': 4, 'u': 5, 'h': 1, 'b': 1, ' ': 13, 'w': 4, 'l': 3, 'c': 1, 'm': 3, 's': 4, 'y': 1, '!': 3, '\n': 2, 'p': 2, 'r': 7, 'v': 2, 'i': 7, 'f': 1, 'n': 6, 't': 4, 'a': 3}
it is a text file
Program 2 :
import collections
import pprint
file_input = "D:\\Komal\\n1\\goeduhub\\python.txt"
with open(file_input, 'r') as info:
count = collections.Counter(info.read().upper())
value = pprint.pformat(count)
print(value)
a=file_input.split(".")
if a[1]=="txt":
print("it is a text file")
elif a[1]=="cpp":
print("it is a c++ file")
else:
print("it is a c file")
Output 2 :
Counter({' ': 25,
'E': 21,
'I': 16,
'N': 16,
'O': 15,
'T': 12,
'S': 11,
'L': 10,
'.': 9,
'U': 8,
'R': 8,
'A': 8,
'W': 7,
'D': 6,
',': 6,
'G': 5,
'H': 5,
'M': 5,
'V': 5,
'C': 4,
'P': 4,
'\n': 3,
'Q': 3,
'F': 2,
'1': 1,
'B': 1,
'2': 1,
'3': 1,
'Y': 1,
'4': 1})
it is a text file
For more Rajasthan Technical University CSE VI Sem Python Lab Experiments Click here