Reputation: 31
When run, the cursor simple blinks on the command line to the left and nothing happens. Could anyone tell me why it does not do what is expected?
Thanks in anticipation.
The code is as follows:
import sys
i=3
try:
text = open(sys.argv[1], 'r')
except IOError:
print 'Cannot open file %s for reading' % filename
sys.exit(0)
char = text.read (1)
#navigate to ith sentence, i.e. go to the first letter of the ith sentence
j = 0
for j in range (0, i-1):
char = text.read (1)
if char == '.':
j = j+1
char = text.read(2) #Assuming there is a spce after full-stop/!/?
#count the number of characters in the present sentence
chars = 0
while char != '.' or '!' or '?':
char = text.read (1)
chars = chars + 1
print chars
Upvotes: 0
Views: 149
Reputation: 304315
When you get to the end of the file, read(1) will just return an empty string every time
Help on built-in function read: read(...) read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given.
Upvotes: 0
Reputation: 1551
I see one problem:
while char != '.' or '!' or '?':
Should be:
while char != '.' and char != '!' and char != '?':
... or at least something logically equivalent, but cleaner and more delicious-looking. In the former case, Python would be trying to evaluate char != '.'
, and then evaluate '!'
, and evaluate '?'
, both considered true
(because they aren't equal to zero). So the loop goes on forever!
As for:
j = 0
for j in range (0, i-1):
char = text.read (1)
if char == '.':
j = j+1
I don't think this does what you intend it to do. Assuming the text file is like 'This is a sentence. This is another sentence.', that loop will set char to 'i' and j to 1. You may have intended to have a while loop, like I described above, instead of a single if statement.
Upvotes: 4