By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,703 Members | 1,214 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,703 IT Pros & Developers. It's quick & easy.

Python string frequency program

P: 3
Expand|Select|Wrap|Line Numbers
  1. x = raw_input("Enter string: ")  
  2.  
  3. def frequencies(x):
  4.     d = dict()      
  5.     for c in x:     
  6.         if c not in d:      
  7.             d[c] = 1        
  8.         else:
  9.             d[c] += 1       
  10.     return d 
How can one rewrite this code to perform the same function for a textfile instead?
May 17 '12 #1

✓ answered by andrean

Expand|Select|Wrap|Line Numbers
  1. filename = 'readlines.txt'
  2. with open(filename, 'r') as text_file:
  3.     x = text_file.read()
  4.  
  5. def frequencies(x):
  6.     d = dict() 
  7.     for c in x: 
  8.         if c not in d: 
  9.             d[c] = 1 
  10.         else:
  11.             d[c] += 1 
  12.     return d 
  13.  
  14. print frequencies(x)
  15.  

Share this Question
Share on Google+
1 Reply

P: 5
Expand|Select|Wrap|Line Numbers
  1. filename = 'readlines.txt'
  2. with open(filename, 'r') as text_file:
  3.     x = text_file.read()
  4.  
  5. def frequencies(x):
  6.     d = dict() 
  7.     for c in x: 
  8.         if c not in d: 
  9.             d[c] = 1 
  10.         else:
  11.             d[c] += 1 
  12.     return d 
  13.  
  14. print frequencies(x)
  15.  
May 17 '12 #2

Post your reply

Sign in to post your reply or Sign up for a free account.