python - Splitting string into different line lengths -
i'm trying split variable length string across different predefined line lengths. i've thrown code below fails on key error 6 when plonk python tutor (i don't have access proper python ide right now) guess means while loop isn't working , it's trying keep incrementing linenum i'm not sure why. there better way this? or fixable?
the code:
import re #dictionary containing line number key , max line length linelengths = { 1:9, 2:11, 3:12, 4:14, 5:14 } inputstr = "this long desc 7x7 needs splitting" #test string, should split on spaces , around "x" splitted = re.split("(?:\s|((?<=\d)x(?=\d)))",inputstr) #splits inputstr on white space , x surrounded numbers eg. dimensions linenum = 1 #initialises line number @ 1 linestr1 = "" #initialises each line 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 longer 40 characters" else: while linenum <= 5: 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() i've taken @ answer don't have real understanding of c#: split large text string variable length strings without breaking words , keeping linebreaks , spaces
it doesn't work because have for words in splitted loop inside loop linelen condition. have this:
if len(inputstr) > 40: print "the short description longer 40 characters" else: word in splitted: if linenum > 5: break 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 also linestr1, linestr2 , on won't changed, have access dict directly (strings immutable). tried , got results working:
print("lines: %s" % linenumdict) gives:
lines: {1: 'this a', 2: 'long desc 7', 3: '7 needs ', 4: '', 5: ''}
Comments
Post a Comment