2

I'm having a slight problem with counting newlines. I'm working on a program that's supposed to count items from a .txt file (characters, upper/lowercase characters, etc.). However, my line counter is counting the amount of character plus one instead of the amount of new lines. For instance, instead of getting something like a character count of 1048 and a line count of 37, I get a character count of 1048 and a line count of 1049. I'm not sure where I messed up.

Below is the relevant code. I appreciate any assistance.

# initializing counters char_count = 0 lower_count = 0 upper_count = 0 lines_count = 0 word_count = 0 prev_ch = ' ' is_prev_alnum = False for ch in contents: char_count += 1 if ch.islower(): lower_count += 1 if ch.isupper(): upper_count += 1 if ch == '\n': lines_count += 1 # count words if ch.isalnum(): if not is_prev_alnum: word_count += 1 is_prev_alnum = True else: is_prev_alnum = False if prev_ch != '\n': lines_count += 1 prev_ch = ch 
1
  • 1
    You're checking if prev_ch != '\n'. I think you mean to check if prev_ch == '\n'. In other words, count a new line for every \n. Commented Oct 28, 2019 at 2:59

1 Answer 1

2

Why do you have

 if prev_ch != '\n': lines_count += 1 

Since prev_ch is already defined as ' ' or a valid ch it is not '\n', it keeps counting it for each loop just like the character

As suggested in the comments, you can just do if prev_ch == '\n'

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

2 Comments

Alright so quick question just for reference, how would I use the prev_ch to add a line to the line count if a .txt only has 1 line but no \n character at the end? Your suggestion works fine for everything else though.
In that case, lines_count value is 0 right? char_count is not zero, then you can assign lines_count = 1 At the end, may be add if char_count != 0 and lines_count=0: lines_count = 1