编写python脚本来解析文本文件中传入的字符串并逐字输出到serial(serial parts注释掉)
获取以下错误:
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
如果文件内容是固定的,则应该只读取一次,并在设置字长之前移动。一个接一个地发送所有已读单词。
如果文件内容发生更改(这可以解释错误),如果新内容短于stringInc的当前值,则可以降低maxLength(仅在读取文件之后),但决不强制stringInc低于此新值,因此会显示错误消息…
在更改maxLength之后添加
if stringInc >= maxLength:
这样的检查应该有助于纠正代码(在这种情况下,我想应该将stringInc设置为0)。但是这个行为还是很奇怪的,我宁愿把文件中所有的字都发一次后再看,而不是一会儿就看,以后再看文件,要发的话只要修改一下就行了
相关问题 更多 >
编程相关推荐