Reputation: 63
one of my python programs is to find the number of sentences, words and letters of a text file and print it off on the screen. I'm slightly confused about how I'm suppose to do this I have some idea on how to get the words but I'm not sure how to get the program to notice how many sentences and letters are in the text file. how do i get the output to print to the screen so i can see whether or not I'm making the correct adjustments. below is the text file I'm suppose to go through with the program.
fname = "gettysburg.txt"
num_lines = 0
num_words = 0
num_chars = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
num_lines += 1
num_words += len(words)
num_chars += len(line)
I have figured out how to print it to the screen, what I do need help on now is how do I make it so it can determine what is a sentence and how to count that. I also need to figure out how to count the characters but without it counting the spaces only the letters.
Upvotes: 3
Views: 4304
Reputation: 28
Use num_chars += len(line.replace(' ', ''))
instead, which removes all spaces from the line.
For sentences (assuming all sentences end with a period and there's no ellipsis in the sentence), you can use the count method: num_lines += line.count(".")
So in your code it would look like:
fname = "gettysburg.txt"
num_lines = 0
num_words = 0
num_chars = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
num_lines += line.count(".")
num_words += len(words)
num_chars += len(line.replace(' ', ''))
Upvotes: 1
Reputation: 386
fname = "gettysburg.txt"
num_lines = 0
num_words = 0
num_chars = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
num_lines += 1
num_words += len(words)
num_chars += len(line)
print(num_lines)
print(num_words)
print(num_chars)
Upvotes: 0