Python string frequency program

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Florrianer
    New Member
    • May 2012
    • 3

    Python string frequency program

    Code:
    x = raw_input("Enter string: ")  
    
    def frequencies(x):
        d = dict()      
        for c in x:     
            if c not in d:      
                d[c] = 1        
            else:
                d[c] += 1       
        return d
    How can one rewrite this code to perform the same function for a textfile instead?
    Last edited by bvdet; May 17 '12, 07:19 PM. Reason: Add code tags
  • andrean
    New Member
    • May 2012
    • 5

    #2
    Code:
    filename = 'readlines.txt'
    with open(filename, 'r') as text_file:
        x = text_file.read()
        
    def frequencies(x):
        d = dict() 
        for c in x: 
            if c not in d: 
                d[c] = 1 
            else:
                d[c] += 1 
        return d 
    
    print frequencies(x)

    Comment

    Working...