python - Function that takes a string representing a filename as an argument. Function returns number of letters in the txt file -
i need write function takes string representing filename argument, e.g. letter_count('alphabet.txt'). function should open file , return number of letters (not digits or other characters) contains.
sorry including doctest think helps make more obvious trying achieved.
def letter_count(filename):     """     >>> letter_count("anthem.txt")     177     >>> letter_count("digits.txt")     0     >>> letter_count("phrase.txt")     10     """      myfile = filename     count = 0     letters = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"     text = myfile.readlines()     char in text:         if char in letters:             count += 1     return count   import string  myfile = open(filename, 'r') myfile.close()  if __name__=="__main__":    import doctest    doctest.testmod(verbose=true) obviously have made mistake cannot pinpoint, advice?
your file being opened outside function.
try this:
def letter_count(filename):     count = 0     letters = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"     open(filename) f:         line in f:             char in line:                 if char in letters:                     count += 1     return count edit: take closer look @ with statement, it's quite handy here.
Comments
Post a Comment