python - Function that counts sentences -


file = open(file_variable) n = 0 line = file.readline()  while line != "":     ch in line:         if ch in '.?!':             n += 1     file.readline()  return n  file_variable.close() 

when try , print n in main program, doesn't return anything. can give me advice on i'm doing wrong. i'm bit confused on how reading txt files works..

main program

from functions import sentence_count  file_variable = 'pelee.txt'  n = sentence_count(file_variable)  print(n) 

you need reset line variable next line of file:

while line != "":     ch in line:         if ch in '.?!':             n += 1     line = file.readline() 

i instead iterate on lines of filelike object this:

f = open('example.txt', 'r')  line in f:     if '.' in line or '?' in line or '!' in line:         n += 1 

this works because python's open() function returns iterable object (io.textiobase) allows navigate contents of file in loop. each item returned iterable next line of file. can check char you're looking find in line variable.


Comments