add new line after number in single-line text file

Viewed 199

I have a single giant string of HPBasic code in a text file such as:

158 ! 159 SUBEXIT 160 ! 161 Prntr_available: ! Cannot allow entry to Test Menu if printer is not 162 ! available; results only go to printer 163 IF Conditions$(15,2)[6,6]<>"*" THEN ! Printer is not available 164 Cond_error=1 165 Prompt_user("ERROR: Printer not available; cannot perform tests.")

Those consecutive numbers are new lines in the code. How can I iterate over this to print a newline before each one of those numbers to make this readable? For now I have:

mystring = ('EnormousString')
myString.replace('1', '1\n')

This kind of works. Is there a way to add +=1 to this? Not sure where to go with it.

4 Answers

You could do something like this:

output = []
curline = 0
for token in s.split(' '):
  try:
    line = int(token)
    if line > curline:
      curline = line
      output.append('\n')
  except:
    pass
  output.append(token)

output_str = ' '.join(output).lstrip() # lstrip removes the leading \n

This doesn’t assume that the line numbers are all one greater than the last (but that could be added), since I believe BASIC only required that it was greater than the previous line. As others have mentioned, this may break if a larger number is in the line (surrounded by white space).

This def will do it (below). It requires that all consecutive line separating numbers occur in order, and I've required that each is flanked by spaces, to reduce the chance that you'll lose info due to (for example) the number 3 occurring in the text that precedes the line 3 separator. To prevent lines from splitting a " 3 " that for some reason occurs after the line 3 separator, I used maxsplit=1 (i.e. str.split([sep[, maxsplit]])), so it only used the first instance of " 3 ":

def split_text(text):
    i, sep, tail = 1, '1 ', text
    while sep in tail:
        head, tail = tail.split(sep, 1)
        print(head)
        i += 1
        sep = ' ' + str(i) + ' '
    print(tail)

Appending it to a file should be straightforward from there.

This assumes the first part of the text will always be a line number, which it should if the input is valid. It also assumes the lines themselves will never contain the next line number between two spaces; this is not a great assumption, but I don't think there's much of a way around that without somehow integrating an HPBasic parser.

code = """158 ! 159 SUBEXIT 160 ! 161 Prntr_available: ! Cannot allow entry to Test Menu if printer is not 162 ! available; results only go to printer 163 IF Conditions$(15,2)[6,6]<>"*" THEN ! Printer is not available 164 Cond_error=1 165 Prompt_user("ERROR: Printer not available; cannot perform tests.")"""
line_number = int(code[:code.index(" ")])

lines = []
string_index = 0

while True:
    line_number += 1

    try:
        next_index = code.index(" " + str(line_number) + " ", string_index)
    except ValueError:
        lines.append(code[string_index:].strip())
        break

    lines.append(code[string_index:next_index].strip())
    string_index = next_index

print "\n".join(lines)
# 158 ! 
# 159 SUBEXIT 
# 160 ! 
# 161 Prntr_available: ! Cannot allow entry to Test Menu if printer is not 
# 162 ! available; results only go to printer 
# 163 IF Conditions$(15,2)[6,6]<>"*" THEN ! Printer is not available 
# 164 Cond_error=1
# 165 Prompt_user("ERROR: Printer not available; cannot perform tests.")

How about replacing with regex whenever 3 digits are found?

import re
mystring = '158 ! 159 SUBEXIT 160 ! 161 Prntr_available: ! Cannot allow entry to Test Menu if printer is not 162 ! available; results only go to printer 163 IF Conditions$(15,2)[6,6]<>"*" THEN ! Printer is not available 164 Cond_error=1 165 Prompt_user("ERROR: Printer not available; cannot perform tests.")'
print((re.sub(r"(\d{3})",r"\n\1", mystring)))

This would give the below output:

158 ! 
159 SUBEXIT 
160 ! 
161 Prntr_available: ! Cannot allow entry to Test Menu if printer is not 
162 ! available; results only go to printer 
163 IF Conditions$(15,2)[6,6]<>"*" THEN ! Printer is not available 
164 Cond_error=1 
165 Prompt_user("ERROR: Printer not available; cannot perform tests.")
Related