1

I have a task to count symbols from multiple text files. I am near to finish but facing an issue. Below is my n I want to sum the commaCount value. I put command total = sum(commacount) but it shows error

total = sum(commaCount)
TypeError: 'int' object is not iterable

Here's my code:

import glob

def stats():

    commaCount = 0

    path = 'D:/Stiudies/Data/female/*.txt'
    inf = glob.glob(path)

    for name in inf:
        with open(name, 'r', encoding="utf8") as input_file:
            for line in input_file:
                for char in line:
                    if char == ',':
                        commaCount += 1

                        total = sum(commaCount)

            print(commaCount)

stats()

3 Answers 3

1

The error comes form the fact that the built-in sum function expects to receive an argument that is something like a list of numbers (an 'iterable') that it will sum together. In your case, you are giving it commaCount, which is a single number (not an iterable).

However, by using:

commaCount += 1

you are already summing up all of the commas in all of the files, so there is no reason to do another sum. I think you can just remove that line.

Sign up to request clarification or add additional context in comments.

Comments

1

Following code helps to find number of ',' per file and total in list of files

import glob
path = 'D:\Stiudies\Data\female\*.txt'
inf = glob.glob(path)
commaCount = 0
for name in inf:
    with open(name, 'r') as input_file:
        count += input_file.read().count(',')
        print "Count:{}\t for file:{}:".format(count,name)
    commaCount +=count
print "Total count:", commaCount

1 Comment

Note that your current answer needs some adaptions for python 3. E.g. print vs print().
0

use count function like this:

a = "hi, hello, good by, , ,"

print(a.count(","))

it will show you:

5

but for your original code:

path = 'D:/Stiudies/Data/female/*.txt'
inf = glob.glob(path)

buffer_commas = 0

for name in inf:
    with open(name, 'r', encoding="utf8") as input_file:
        raw_data = input_file.read()
        buffer_commas = buffer_commas + raw.count(",")

print(buffer_commas)

2 Comments

Thank you for your help code is working fine. i want to count uppercase characters as well. Please help me with that. Thank you.
@MuhammadHafizTahir : use print(sum(1 for c in your_string if c.isupper()))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.