string - Trying to count letter frequency in text file in Python -


i have program count letters in specific text file, (in example, "words.txt"). however, when try change code accept user input instead of looking specific file, following:- 'str' object has no attribute 'readlines'

i sure sill doing, cannot see why. code below:

import string #fname=raw_input("enter file name: ") fname=open('words.txt', 'r')  #if len(fname) < 1 : fname = "words.txt" file_list = fname.readlines()  freqs = dict() line in file_list: line = filter(lambda x: x in string.letters, line.lower()) char in line:     if char in freqs:         freqs[char] += 1     else:         freqs[char] = 1 lst = list() key, val in freqs.items():   lst.append( (val, key) )  lst.sort(reverse=true)  key, val in lst[:] :     print key, val 

what raw_input string holding name of file. still have open actual file handle.

filename = raw_input("enter file name: ") fname = open(filename, 'r') 

also, might want use with file automatically closed @ end of execution. , instead of reading lines list, can iterate file directly.

filename = raw_input("enter file name: ") open(filename, 'r') fname:     freqs = dict()     line in fname:         ... 

finally, might take @ collections.counter...


Popular posts from this blog