index应该在范围内......但不是

时间:2013-06-03 18:59:55

标签: python list indexing range grammar

我正在尝试编写代码来检查某人是否在同一个句子中切换了时态。它从文本框中获取数据,将其分成句子,将这些句子分成单词,并根据不同时态的动词列表检查单词。如果句子不一致,则会突出显示。我已经成功完成了这个,但是当我返回时,我还想在文本框中保持文本的格式相同。程序也是如此,但是如果一个段落的第一句不一致,它将突出显示第一段和句子之间的所有空格。我尝试运行if语句,查找扩展的空格并将其与句子分开,因此荧光笔不会将其作为句子的一部分包含在内。但我不断收到此错误:IndexError: list index out of range

任何帮助都将不胜感激。

以下是相关代码:

def verbTense(self):#Checks sentences for inconsistent tenses
    text=self.input.get(1.0,'end')
    self.input.delete(1.0,'end')
    text=sentenceSplit(text)
    self.input.tag_config('verb',background='yellow')
    for i in text:
        if inconsistentTense(i)==True:
            self.input.insert('end',i,'verb')
        else:
            self.input.insert('end',i)

def sentenceSplit(x):#Splits a string into sentences.
    fullText=[]
    tempSentence=[]
    x=formatSplit(x)
    index=0
    for i in x:
        if i==" " and x[index+1]==" ":
            fullText.append(i)
        else:
            if ".)" in i or "!" in i or "?" in i or "." in i or "!)" in i or "?)" in i or ")" in i or "]" in i or "}" in i:
                tempSentence.append(i)
                sentence=listIntoWord(tempSentence)
                fullText.append(sentence)
                tempSentence=[]
            else:
                tempSentence.append(i)
        index+=1
    return fullText

def listIntoWord(x):#Combines list of strings into one single string.
    text=""
    for i in x:
        text+=str(i)
    return text

def formatSplit(x):#Splits a string into different words while keeping the spaces. 
    wordString=[]
    totalString=[]
    for i in x:
        if i==" ":
            wordString=listIntoWord(wordString)
            totalString.append(wordString)
            wordString=[]
            totalString.append(i)
        else:
            wordString.append(i) 
    return totalString

2 个答案:

答案 0 :(得分:1)

def sentenceSplit(x):#Splits a string into sentences.
    fullText=[]
    tempSentence=[]
    x=formatSplit(x)
    index=0
    for i in x:
        if i==" " and x[index+1]==" ":  # THIS LINE COULD BE PROBLEMATIC AT LAST ITERATION
            fullText.append(i)

在循环结束时index将指向字符串中的最后一个字符,访问x[index+1]会引发IndexError。

答案 1 :(得分:1)

您的问题在于sentenceSplit()

中的这些代码行
index=0
for i in x:
    if i==" " and x[index+1]==" ":
        ...
    ...
    index+=1

此循环的主体将执行len(x)次,在最后一次迭代indexlen(x)-1,因此x[index+1]将等同于x[len(x)] }。这将导致IndexError,因为序列x中的最后一项位于索引len(x)-1,因此len(x)已超过序列的末尾。

要解决此问题,您可以执行以下两项操作之一:

  • 只循环到倒数第二个项目,所以当你向前看每次迭代时,你永远不会传递序列的结尾:

    for index, i in enumerate(x[:-1]):
        if i == " " and x[index+1] == " ":
            ...
    
  • 不要检查最后一次迭代的下一个项目:

    for index, i in enumerate(x):
        if i == " " and (index == len(x)-1 or x[index+1] == " "):
            ...
    

您可以选择更适合您的代码。

请注意,我还修改了代码,使其使用enumerate(),这是循环遍历项目和索引的首选方法。