我正在尝试将可变长度字符串拆分为不同但预定义的行长。我把下面的一些代码放在一起,当我将它插入Python Tutor时,这些代码在关键错误 6 上失败(我现在无法访问适当的 python IDE)我想这意味着我的 while 循环不能正常工作而且它是试图继续增加 lineNum 但我不太清楚为什么。有一个更好的方法吗?或者这很容易解决吗?
编码:
import re
#Dictionary containing the line number as key and the max line length
lineLengths = {
1:9,
2:11,
3:12,
4:14,
5:14
}
inputStr = "THIS IS A LONG DESC 7X7 NEEDS SPLITTING" #Test string, should be split on the spaces and around the "X"
splitted = re.split("(?:\s|((?<=\d)X(?=\d)))",inputStr) #splits inputStr on white space and where X is surrounded by numbers eg. dimensions
lineNum = 1 #initialises the line number at 1
lineStr1 = "" #initialises each line as a string
lineStr2 = ""
lineStr3 = ""
lineStr4 = ""
lineStr5 = ""
#Dictionary creating dynamic line variables
lineNumDict = {
1:lineStr1,
2:lineStr2,
3:lineStr3,
4:lineStr4,
5:lineStr5
}
if len(inputStr) > 40:
print "The short description is longer than 40 characters"
else:
while lineNum <= 5:
for word in splitted:
if word != None:
if len(lineNumDict[lineNum]+word) <= lineLengths[lineNum]:
lineNumDict[lineNum] += word
else:
lineNum += 1
else:
if len(lineNumDict[lineNum])+1 <= lineLengths[lineNum]:
lineNumDict[lineNum] += " "
else:
lineNum += 1
lineOut1 = lineStr1.strip()
lineOut2 = lineStr2.strip()
lineOut3 = lineStr3.strip()
lineOut4 = lineStr4.strip()
lineOut5 = lineStr5.strip()
我看过这个答案,但对 C# 没有任何真正的理解:将大文本字符串拆分为可变长度字符串,而不破坏单词并保留换行符和空格