Objectives:: 10.3 Take Any TXT File and Count Word Frequencies in A File. (Hint: File Handling+basics)
Objectives:: 10.3 Take Any TXT File and Count Word Frequencies in A File. (Hint: File Handling+basics)
Objectives:
1. To learn about python as scripting option.
Theory:
File handling:
A file is some information or data which stays in the computer storage devices. You already
know about different kinds of file , like your music files, video files, text files. Python gives you
easy ways to manipulate these files. Generally we divide files in two categories, text file and
binary file. Text files are simple text where as the binary files contain binary data which is only
readable by computer.
File opening:
To open a file we use open() function. It requires two arguments, first the file path or file name,
second which mode it should open. Modes are like
“r” -> open read only, you can read the file but can not edit / delete anything inside
“w” -> open with write power, means if the file exists then delete all content and open it
to write
“a” -> open in append mode
The default mode is read only, ie if you do not provide any mode it will open the file as
read only. Let us open a file
>>> fobj = open("love.txt")
>>> fobj
Closing a file:
After opening a file one should always close the opened file. We use method close() for this.
>>> fobj = open("love.txt")
>>> fobj
>>> fobj.close()
Reading a file:
>>> fobj.read()
Program:
f=open("10cfile.txt")
d={}
for line in f:
l=line.split()
#print(line)
#print(l)
for word in l:
#print(word)
if word in d:
d[word]=d[word]+1
else:
d[word]=1
for key in d:
print key," : ",d[key]
Output:
it@it-OptiPlex-3046:~$ python uox10.py
a: 2
A: 1
Peter : 4
of : 4
Piper : 4
pickled : 4
Where's : 1
picked : 4
peppers : 4
the : 1
peck : 4
If : 1
Conclusion:
File handling and manipulation of data using list and dicitionary learnt.
5