简体   繁体   English

使用 Python 查找给定文本文件的第 i 个句子中的字符数

[英]Finding the number of characters in the ith sentence of a given text file using Python

When run, the cursor simple blinks on the command line to the left and nothing happens.运行时,cursor 在左侧命令行上简单闪烁,没有任何反应。 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

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.= '.'在前一种情况下,Python 将尝试评估char.= '.' , and then evaluate '!' , 然后评估'!' , and evaluate '?' , 并评估'?' , both considered true (because they aren't equal to zero). ,两者都被认为是true (因为它们不等于零)。 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.这是另一个句子。',该循环会将 char 设置为 'i' 并将 j 设置为 1。您可能打算使用 while 循环,就像我上面描述的那样,而不是单个 if 语句。

When you get to the end of the file, read(1) will just return an empty string every time当您到达文件末尾时, read(1) 每次都会返回一个空字符串

    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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM