编写python脚本来解析文本文件中的传入字符串,并逐字输出到串行(串行部分被注释掉)
获取以下错误:
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我知道这与新的列表(当文本文件的内容比以前的列表包含的单词要少得多)没有足够高的索引号来工作有关。我不太确定该如何补救这一点。任何帮助都将不胜感激。完整代码如下:
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发布于 2019-01-29 07:19:30
如果文件内容是固定的,则应该只读一次,并在设置wordLength之前移动while。一个接一个地发送所有已读的单词。
如果文件内容发生更改,这将解释错误,如果新内容比stringInc的当前值短,您可以降低maxLength (就在读取文件之后),但永远不会强制stringInc低于这个新值,因此出现错误消息...
在更改maxLength之后添加一个像if stringInc >= maxLength:这样的检查应该有助于纠正代码(在这种情况下,我想应该将stringInc设置为0 )。
但这种行为仍然很奇怪,我宁愿在读完一次文件后发送文件的所有字,而不是在一段时间内读完它,然后再读一次文件,只有在修改的情况下才会发送...
https://stackoverflow.com/questions/54410994
复制相似问题