编写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
答案 0 :(得分:0)
如果文件内容固定,则应仅读取一次,并在设置wordLength之前移动一会儿。依次发送所有已读单词。
如果文件内容发生变化(这可以解释该错误),如果新内容短于stringInc的当前值,则可以降低maxLength(仅在读取文件后),但绝不要强迫stringInc低于此新值,因此错误消息...
在更改maxLength之后添加类似if stringInc >= maxLength:
的检查应该有助于更正代码(我想在这种情况下,将stringInc设置为0)。
但是这种行为仍然很奇怪,我宁愿在一次读取文件后发送文件中的所有单词,而不是在一段时间内不读取它,然后稍后再次读取该文件,以仅在修改后才发送... >