[英]add new line after number in single-line text file
我在文本文件中有一个巨大的HPBasic代码字符串,例如:
158! 159 SUBEXIT 160! 161 Prntr_available:! 如果打印机不是162,则无法进入测试菜单! 可用的; 结果只有打印机163如果条件$(15,2)[6,6] <>“*”那么! 打印机不可用164 Cond_error = 1 165 Prompt_user(“错误:打印机不可用;无法执行测试。”)
这些连续的数字是代码中的新行。 我如何迭代这个以在每个这些数字之前打印换行符以使其可读? 现在我有:
mystring = ('EnormousString')
myString.replace('1', '1\n')
这种作品。 有没有办法为此添加+=1
? 不知道该去哪里。
你可以这样做:
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
这并不是假设行号都比最后一行大(但可以添加),因为我认为BASIC只要求它大于前一行。 正如其他人所提到的,如果行中有更大的数字(由空格包围),这可能会中断。
这个def会做(下图)。 它要求所有连续的行分隔数按顺序出现,并且我要求每个行都有空格,以减少由于(例如)在前面的文本中出现的数字3而丢失信息的可能性。第3行分隔符。 为了防止行分裂“3”,由于某种原因发生在第3行分隔符之后,我使用了maxsplit = 1(即str.split([sep[, maxsplit]])
),所以它只使用了第一个实例“ 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)
将其附加到文件应该是直截了当的。
这假定文本的第一部分将始终是行号,如果输入有效,则应该是行号。 它还假设行本身永远不会包含两个空格之间的下一个行号; 这不是一个很好的假设,但是如果不以某种方式集成HPBasic解析器,我认为没有太多的方法。
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.")
如果找到3位数,如何用正则表达式替换?
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)))
这将给出以下输出:
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.")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.