Carl Carl - 1 year ago 63
Python Question

How to use string methods on text files?

I have to write a program where I need to find

  • the number of uppercase letters

  • the number of lowercase letters

  • the number of digits

  • the number of whitespace characters

in a text file and my current code is

def lowercase(line_list):

print("Lower case Letters: ", sum(1 for x in line_list if x.islower))

def uppercase(line_list):

print("Upper case Letters: ", sum(1 for c in line_list if c.isupper())

def numbers(line_list):

print("Numbers: ", sum(1 for b in line_list if b.isdigit())

def whitespace(line_list):

print("Spaces: ", sum(1 for y in line_list if y.isspace())

def main():

in_file = open("text.txt", "r")

line = in_file.readline()

line_list = line.split()







However whenever I try to run the script it gives me a syntax error. Is there something I am doing wrong?

Answer Source

Right now, you have a syntax error in your lowercase function (you're missing the parens for the function call islower). However, your main function also has some problems. Right now, you are only reading in one line of the file. Also, you're splitting that line (split splits using space by default, so you will lose the spaces you are trying to count). If you're trying to read the whole thing, not just one line. Try this:

def main():
    lower_case = 0
    upper_case = 0
    numbers = 0
    whitespace = 0
    with open("text.txt", "r") as in_file:
        for line in in_file:
            lower_case += sum(1 for x in line if x.islower())
            upper_case += sum(1 for x in line if x.isupper())
            numbers += sum(1 for x in line if x.isdigit())
            whitespace += sum(1 for x in line if x.isspace())

    print 'Lower case Letters: %s' % lower_case
    print 'Upper case Letters: %s' % upper_case
    print 'Numbers: %s' % numbers
    print 'Spaces: %s' % spaces

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download