我正在尝试将一个可变长度的字符串拆分为不同但预定义的行长度。我把下面的一些代码放到Python Tutor(我现在没有权限访问一个合适的python IDE)时,它们在键错误6上失败了,我想这意味着我的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没有真正的理解:Split large text string into variable length strings without breaking words and keeping linebreaks and spaces
我想知道一个正确注释的正则表达式是否更容易理解?在
另外,使用dict来表示行长度并没有实际意义,列表就可以了。在
您的代码将
lineNum
增加splitted
中的字数,即16倍。在它不起作用,因为在循环中使用lineLen条件的for words在分割的循环中。你必须这样做:
而且lineStr1、lineStr2等不会更改,您必须直接访问dict(字符串是不可变的)。我试了一下,结果奏效了:
^{pr2}$给出:
相关问题 更多 >
编程相关推荐