How to open and find the number of words within a file with a list of strings in different txt files

587 views python
2

I have to create a function named processFiles that takes a list of strings(list of filenames) as a parameter. The function should open each print the total number of words in all of the files in list of filenames on one line and the average number of words per file on the following line.

I'm completely confused as to where I even start. This is what I have to do(this is just an example):

list of filenames is equal to ['input1.txt','input2.txt','input3.txt']

with the above files containing the following information:

imput1.txt contains the words The quick brown fox input2.txt contains the words jumped over input3.txt contains the words the lazy dog

Your function should print: 9 for word total 3 for word average

answered question

What difficulty are you having in doing so that someone can help with? Do you know how to open a file, read a line, split a string, loop over lists? That's all the bits you need to put together to do this...

2 Answers

12

For instance you can do it like so:

files = ["foo.txt", "bar.txt"]

def proces_files(files):
    for f in files:
        with open(f, "r") as f:
            content = f.readlines()
            total = 0
            for line in content:
                words = line.split(" ")
                total += len(words)
                print("Total number of words: {0:d}".format(len(words)))

            avg = (total / len(content))
            print("Average quantity of words per line {0:d}".format(avg))

proces_files(files)

Sample output:

Total number of words: 3
Total number of words: 2
Total number of words: 4
Average quantity of words per line 3
Total number of words: 4
Total number of words: 2
Average quantity of words per line 3

posted this
3

You can read all the files consequently and append their content to a list. Then evaluate the number of words in the list.

files = ['input1.txt', 'input2.txt', 'input3.txt]
l = []
num_files = 0;
for file in files:
    with open(file) as f:
        l.append(f.readlines())
        num_files += 1

num_of_words = len(str(l).split())
print(num_of_words)
avg = num_of_words/num_files     //average

posted this

Have an answer?

JD

Please login first before posting an answer.