简体   繁体   中英

Python: counter in a function with multiple args

Working on a function for input of an arbitrary number of text files as args. Function is to count lines, words and chars for each of the files, as well as a total count:

lines = words = chars = 0

def cfunc(folder, *arg):
    global lines, words, chars

    for x in arg:
        with open("{}{}".format(folder, x), "r") as inp:
            for line in inp:
                lines += 1
                words += len(line.split(" "))
                chars += len(line)
        print(x, lines, words, chars)

cfunc("C:/", "text1.txt", "text2.txt", "text3.txt")

The counter is correct for the first file. For the third the counter essentially shows the total number for lines/words/chars across all 3 files. As i understand, this happens because inp reads all 3 files together and the counter is the same across all files. How could i separate the counters to print statistics for each file individually?

First, you need to reset your statistics for each file:

for x in arg:
    lines = words = chars = 0
    with open("{}{}".format(folder, x), "r") as inp:
        ...

Second, to keep a total count you need to use separate variables since you're now resetting the variables for each iteration:

total_lines = total_words = total_characters = 0

def cfunc(folder, *arg):
    global total_lines, total_words, total_chars

    for x in arg:
        ...
        print(x, lines, words, chars)
        total_lines += lines
        total_words += words
        total_chars += chars

Of course you can name your global variables lines , words , and chars if you want, you then just have to use different names for the variables you use inside the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM