我正在尝试编写代码来检查某人是否在同一个句子中切换了时态。它从文本框中获取数据,将其拆分为句子,将这些句子拆分为单词,并根据不同时态的动词列表检查单词。如果句子不一致,则会突出显示。我已经成功完成了这么多,但是我还想在返回时保持文本框中文本的格式相同。该程序也这样做,但是如果一个段落的第一句不一致,它将突出显示第一段和该句子之间的所有空格。我尝试运行一个 if
语句来查找扩展的空格并将其与句子分开,因此荧光笔不会将其包含在句子中。但是,我不断收到此错误:IndexError:列表索引超出范围
。
如有任何帮助,我们将不胜感激。
相关代码如下:
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
最佳答案
您的问题出在 sentenceSplit()
中的这些代码行:
index=0
for i in x:
if i==" " and x[index+1]==" ":
...
...
index+=1
该循环的主体将被执行len(x)
次,在最后一次迭代 index
将是len(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()
,这是循环项目和索引的首选方式。
关于python - 索引应该在范围内...但不是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16903906/