[Tutor] program idea
Sean 'Shaleh' Perry
shalehperry@attbi.com
Thu May 15 21:34:32 2003
And here is a version which actually honors MAX_LEN (doh!) as well as deal
with cases where the line will be longer than MAX_LEN. The idea is if the
line would be to long just skip the line count for that line. There should
be enough context to make this be ok.
#! /usr/bin/python # 1
# 2
import sys # 3
# 4
def compute_padding(num): # 5
pad = 0 # 6
while num > 0: # 7
num /= 10 # 8
pad += 1 # 9
return pad # 10
# 11
def add_lineno(lines, fp = sys.stdout): # 12
MAX_LEN = 80 # 13
# 14
trailer_gen = "# %%%ds" % compute_padding(len(lines)) # 15
# 16
count = 0 # 17
# 18
for line in lines: # 19
line = line.rstrip() # 20
count += 1 # 21
trailer = trailer_gen % count # 22
pad = MAX_LEN - len(trailer) - len(line) # 23
if pad <= 0: # 24
fp.write("%s\n" % line) # 25
else: # 26
output_gen = "%%s%%%ds\n" % (pad) # this makes the line too long
fp.write(output_gen % (line, trailer)) # 28
# 29
def sub_lineno(lines, fp = sys.stdout): # 30
import re # 31
stripper = re.compile(r'#\s+\d+$') # 32
for line in lines: # 33
fp.write(stripper.sub('', line)) # 34
# 35
if __name__ == '__main__': # 36
if len(sys.argv) > 1 and sys.argv[1] == 'sub': # 37
lines = sys.stdin.readlines() # 38
sub_lineno(lines) # 39
else: # 40
lines = sys.stdin.readlines() # 41
add_lineno(lines) # 42