Wednesday, September 4, 2013

Word count programs in Python



text file a.txt:     
      India is my country and all Indians are my brothers and sisters.I love my country and I am proud of its rich and varied heritage.I shall always strive to be worthy of it.I shall give my parents, teachers and all elders respect and treat everyone with courtesy.To my country and my people, I pledge my devotion. In their well-being and prosperity alone lies my happiness.
 >>>from collections import Counter  
 >>>import re  
 >>>import os  
 >>>list_word=re.findall("\w+",open('a.txt').read().lower())  
 >>>for i in Counter(list_word):
 . . .  print i,'-',Counter(list_word)[ i ]  

#
and - 8
all - 2
everyone - 1
love - 1
pledge - 1
give - 1
being - 1
is - 1
india - 1
it - 1
alone - 1
are - 1
in - 1
respect - 1
its - 1
happiness - 1
prosperity - 1
varied - 1
their - 1
indians - 1
to - 2
parents - 1
treat - 1
rich - 1
heritage - 1
be - 1
brothers - 1
elders - 1
shall - 2
am - 1
of - 2
courtesy - 1
worthy - 1
sisters - 1
with - 1
people - 1
strive - 1
lies - 1
i - 5
country - 3
proud - 1
well - 1
teachers - 1
always - 1
my - 8
devotion - 1

another program for word count:
 >>>d={}  
 >>> list_word=re.findall("\w+",open('a.txt').read().lower())  
 >>>for i in list_word:  
 . . .   d[i]=d.get(i,0)+1  
 >>>d  
# dict of word as above

another program for word count:
 >>> list_word=re.findall("\w+",open('a.txt').read().lower())  
 >>> for i in list(set(list_word)):  
 . . .  print i,list_word.count(i)  


No comments:

Post a Comment