首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python错误: IndexError wordLength = len(wordList[stringInc])

Python错误: IndexError wordLength = len(wordList[stringInc])
EN

Stack Overflow用户
提问于 2019-01-29 06:06:49
回答 1查看 41关注 0票数 0

编写python脚本来解析文本文件中的传入字符串,并逐字输出到串行(串行部分被注释掉)

获取以下错误:

代码语言:javascript
复制
Traceback (most recent call last):
  File "/Users/di/Desktop/RBDS/rbdsScroll.py", line 23, in <module>
    wordLength = len(wordList[stringInc])
IndexError: list index out of range

我知道这与新的列表(当文本文件的内容比以前的列表包含的单词要少得多)没有足够高的索引号来工作有关。我不太确定该如何补救这一点。任何帮助都将不胜感激。完整代码如下:

代码语言:javascript
复制
import time
#import serial
from config import dataPath
from config import scrollTime
from config import preText
from config import postText
from config import port

stringInc=wordFirst=wordLast=wordList=wordLength=word2Length=0

while True:
    f = open(dataPath, 'r')
    file_contents = f.read()
    f.close()

    wordList = file_contents.split()
    maxLength = len(wordList)
    wordLength = len(wordList[stringInc])

    if stringInc < maxLength - 1:
        word2Length = len(wordList[stringInc + 1])

    wordFirst = 0
    wordLast = 8

    if wordLength > 8:
        longString = (wordList[stringInc])

        while wordLength + 1 > wordLast:
#            ser = serial.Serial(port)
#            ser.write(preText + longString[wordFirst:wordLast] + postText)
#            ser.close()

            print(preText + longString[wordFirst:wordLast] + postText)
            wordFirst = wordFirst + 1
            wordLast = wordLast + 1
            time.sleep(scrollTime / 1000)

    elif (wordLength + word2Length < 8) and (stringInc + 1 < maxLength):
#        ser = serial.Serial(port)
#        ser.write(preText + wordList[stringInc] + " " + wordList[stringInc + 1] + postText)
#        ser.close()

        print(preText + wordList[stringInc] + " " + wordList[stringInc + 1] + postText)
        stringInc = stringInc + 1
        time.sleep(scrollTime / 1000)

    else:
#        ser = serial.Serial(port)
#        ser.write(preText + wordList[stringInc] + postText)
#        ser.close()

        print(preText + wordList[stringInc] + postText)
        time.sleep(scrollTime / 1000)

    stringInc = stringInc + 1

    if stringInc == maxLength:
        stringInc = 0
EN

回答 1

Stack Overflow用户

发布于 2019-01-29 07:19:30

如果文件内容是固定的,则应该只读一次,并在设置wordLength之前移动while。一个接一个地发送所有已读的单词。

如果文件内容发生更改,这将解释错误,如果新内容比stringInc的当前值短,您可以降低maxLength (就在读取文件之后),但永远不会强制stringInc低于这个新值,因此出现错误消息...

在更改maxLength之后添加一个像if stringInc >= maxLength:这样的检查应该有助于纠正代码(在这种情况下,我想应该将stringInc设置为0 )。

但这种行为仍然很奇怪,我宁愿在读完一次文件后发送文件的所有字,而不是在一段时间内读完它,然后再读一次文件,只有在修改的情况下才会发送...

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54410994

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档