add new line after number in single-line text file
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', '1n')
This kind of works. Is there a way to add +=1
to this? Not sure where to go with it.
python python-3.x
add a comment |
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', '1n')
This kind of works. Is there a way to add +=1
to this? Not sure where to go with it.
python python-3.x
add a comment |
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', '1n')
This kind of works. Is there a way to add +=1
to this? Not sure where to go with it.
python python-3.x
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', '1n')
This kind of works. Is there a way to add +=1
to this? Not sure where to go with it.
python python-3.x
python python-3.x
edited Nov 15 '18 at 4:20
Ishara Madhawa
2,18441029
2,18441029
asked Nov 15 '18 at 3:20
Marc AlbertMarc Albert
161
161
add a comment |
add a comment |
4 Answers
4
active
oldest
votes
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"(d3)",r"n1", 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.")
add a comment |
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.")
add a comment |
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.
add a comment |
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).
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53311922%2fadd-new-line-after-number-in-single-line-text-file%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
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"(d3)",r"n1", 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.")
add a comment |
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"(d3)",r"n1", 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.")
add a comment |
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"(d3)",r"n1", 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.")
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"(d3)",r"n1", 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.")
answered Nov 15 '18 at 6:37
Ashok KSAshok KS
191214
191214
add a comment |
add a comment |
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.")
add a comment |
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.")
add a comment |
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.")
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.")
edited Nov 15 '18 at 7:13
answered Nov 15 '18 at 6:25
kungphukungphu
2,80911424
2,80911424
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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 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.
edited Nov 15 '18 at 19:23
answered Nov 15 '18 at 5:18
mRottenmRotten
25029
25029
add a comment |
add a comment |
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).
add a comment |
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).
add a comment |
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).
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).
edited Nov 16 '18 at 4:57
answered Nov 15 '18 at 4:27
GniemGniem
914
914
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53311922%2fadd-new-line-after-number-in-single-line-text-file%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown