Total number of lines and words in a file

326 views Asked by At

I have an exercise that is asking to calculate the number of lines and words in an email file, excluding the subject line.

I can get the total number of lines and words with the following code:

file = "email.txt" 
num_lines = 0
num_words = 0
with open(file, 'r') as f:
    for line in f:
        words = line.split() 
        if not line.startswith ('Subject'):
                num_lines += 1
                num_words += len(words)
        
print(num_lines)
print(num_words)

I would like to define a function to get the same information however, the second function for the word count is not return the desired value.

textFile = "email.txt"

def count_lines():
    with open (textFile, 'r') as file:
        num_lines = 0
        for line in file:
            words = line.split()
            if not line.startswith ('Subject'):
                num_lines = num_lines + 1
        return num_lines

def count_words():
    with open (textFile, 'r') as file:
        num_words = 0
        for words in file:
            words = line.split()
            if not line.startswith ('Subject'):
                num_words = num_words + 1
        return num_words

print(count_lines())
print(count_words())
        
1

There are 1 answers

1
Gabio On

I would suggest you another solution, using list comprehension:

with open(textFile, 'r') as f:
    words_per_line = [len(line.split()) for line in f.readlines() if not line.startswith('Subject')]
    total_lines = len(words_per_line)
    total_words = sum(words_per_line)

Where words_per_line contains number of words per line in your file so if you count it (len) you will get the number of lines and if you sum it, you will get the total number of words.