这是在《K&R》上看到的一个习题: 用若干个空格替换掉源程序文件中的tab字符 。自己用Python写了个。
没考虑文件编码、解码(因为自己并不了解),错误处理也不好。 不过勉强可以工作。
# !/usr/bin/env python3
# Filename: detab.py
import os
import sys
print('======================== detab.py ========================')
print(sys.version)
if len(sys.argv) < 2:
print('No action specified.')
input('--------------------Press any key to quit.--------------------')
sys.exit()
if sys.argv[1].startswith('--'):
option = sys.argv[1][2:]
# fetch sys.argv[1] but without the first two characters
if option == 'version':
print(os.linesep + 'Version 1.0, 2011/11/19 by mayadong7349.')
elif option == 'help':
print(r'''
This program exchanges '\t' with several space characters
(specified by you) in your source code.
Usage:
detab.py --version: Prints the version number
detab.py --help: Display this help
detab.py filename_1 filename_2 ...
''')
else:
try:
print()
nums = int(input('''Now I'd like to know how many space characters you want
(4 or 8 is especially recommanded) ? ''' + os.linesep))
except ValueError:
print('You have inputed the wrong number, but I can also work as 4 is taken by default.' + os.linesep)
nums = 4
for srcfile in sys.argv[1:]:
# open file for reading
fin = open(srcfile)
#
(fpath, fname_ext) = os.path.split(os.path.abspath(fin.name))
(fname, fext) = os.path.splitext(fname_ext)
# open file for writing
destfile = fpath + os.path.sep + fname + '_without_tab' + fext
fout = open(destfile, 'w')
# exchange '\t' with ' ' in old file, and write into a new file
while True:
line = fin.readline()
if len(line) == 0:
break
line = line.replace('\t', nums * ' ') # Caution: Here you mustn't lose 'line ='
fout.write(line)
# close all the files opened
fout.close()
fin.close()
print(os.linesep + 'Success: %s --> %s' %(srcfile, destfile))
input('--------------------Press any key to quit.--------------------')
第二个版本:
# !/usr/bin/env python3
# Filename: detab.py
import os
import sys
def pause():
input('--------------------Press any key to quit.--------------------')
def errmsg(msg):
print(msg)
pause()
sys.exit()
usage_str = r"""This program exchanges '\t' with several space characters
(specified by you) in your source code.
Usage:
detab.py --version: Prints the version number
detab.py --help: Display this help
detab.py filename_1 filename_2 ..."""
if len(sys.argv) < 2:
errmsg('No action specified.')
if sys.argv[1].startswith('--'):
option = sys.argv[1][2:]
# fetch sys.argv[1] but without the first two characters
if option == 'version':
print('Version 1.0, 2011/11/19 by mayadong7349.')
elif option == 'help':
print(usage_str)
else:
errmsg('Bad command.' + os.linesep + usage_str)
else:
try:
print()
nums = int(input('''Now I'd like to know how many space characters you want
(4 or 8 is especially recommanded) ? ''' + os.linesep))
except ValueError:
print('You have inputed the wrong number, but I can also work as 4 is taken by default.' + os.linesep)
nums = 4
for srcfile in sys.argv[1:]:
# open file for reading
fin = open(srcfile)
#
(fpath, fname_ext) = os.path.split(os.path.abspath(fin.name))
(fname, fext) = os.path.splitext(fname_ext)
# open file for writing
destfile = fpath + os.path.sep + fname + '_without_tab' + fext
fout = open(destfile, 'w')
# exchange '\t' with several space characters in old file, and write into a new file
while True:
line = fin.readline()
if len(line) == 0:
break
# line = line.replace('\t', nums * ' ')
# Caution: Here you mustn't lose 'line =', as string object can not be changed. In fact, when
# you call a method of your sting object, python will create a new object and return it.
fout.write(line.replace('\t', nums * ' '))
# close all the files opened
fout.close()
fin.close()
print(os.linesep + 'Success: %s --> %s' %(srcfile, destfile))
pause()
2011-12-18:
#-------------------------------------------------------------------------------
# Name: detab.py
# Purpose: replace the tab character by several space characters
# in a C or C++ source file.
# Author: mayadong7349
# Created: 18/12/2011
# Copyright: (c) mayadong7349 2011
# Licence: GPL
#-------------------------------------------------------------------------------
# !/usr/bin/env python3
# Filename: detab.py
import os
import sys
def pause():
input('Press any key to quit.')
def errmsg(msg):
print(msg)
pause()
sys.exit()
def main():
usage_str = r"""This program exchanges '\t' with several space characters
(specified by you) in your source code.
Usage: detab.py option
detab.py <file list>
Options:
--version: Prints the version number
--help: Display this help
"""
if len(sys.argv) < 2:
errmsg('No action specified.')
if sys.argv[1].startswith('--'):
option = sys.argv[1][2:]
# fetch sys.argv[1] but without the first two characters
if option == 'version':
print('Version 1.0, 2011/11/19 by mayadong7349.')
elif option == 'help':
print(usage_str)
else:
errmsg('Bad command.' + os.linesep + usage_str)
else:
try:
print()
nums = int(input('''Now I'd like to know how many space characters you want
(4 or 8 is especially recommanded) ? ''' + os.linesep))
except ValueError:
print('You have inputed the wrong number, but I can also work as 4 is taken by default.' + os.linesep)
nums = 4
for srcfile in sys.argv[1:]:
destfile = srcfile
# rename the old file by adding a '.old' extension.
os.rename(srcfile, srcfile + '.old')
srcfile = srcfile + '.old'
# open file for reading
fin = open(srcfile)
# open file for writing
fout = open(destfile, 'w')
# exchange '\t' with several space characters in old file, and write into a new file
for eachLine in fin:
fout.write(eachLine.replace('\t', nums * ' '))
# close all the files opened
fout.close()
fin.close()
print(os.linesep + 'Success: %s --> %s' %(srcfile, destfile))
pause()
if __name__ == '__main__':
main(
以后会持续修改吧!