Python Programing Lab R16 EXERCISE - 6(b)
Aim:
Write a program to count frequency of characters in a given file. Can you use character frequency to tell whether the given file is a Python program file, C program file or a text file?
Description:
Traverse each character in the file and its occurrence is stored in the dictionary. Here, We are using the concept of files and a Dictionary.
Files:
Python provides basic functions and methods necessary to manipulate files by default. Some of the useful functions in this program are:
open():
Before we can read or write a file, we have to open it using Python‟s built-in open(). This function creates a file object, which would be utilized to call other support methods associated with it.
The Syntax for opening a file object in Python is:
file_object = open(“Name of the file”,”Mode of the file”)
read():
If we need to extract string that contains all characters in the file, We can use read().
TheSyntax for read() in Python is:
TheSyntax for read() in Python is:
str = file_object.read()
Dictionary:
The dictionary is Python‟s built-in mapping type. Dictionaries map keys to values and these <key,value> pairs provides a useful way to store data in python. The only way to access the value part of the dictionary is by using the key.
We can specify the dictionary <key,value> pairs between '{' and '}'. <key,value> pairs arespecified as a list(separated by commas).
Program:
from collections import Counter
with open('netaji.txt','r') as f:
c=Counter()
for x in f:
print(x)
c+=Counter(x.strip())
print(c)
Output:
No comments