Python 字计数和/或行计数程序的参数解析器
在本例中,如何使代码干燥? 打印的字和行在重复Python 字计数和/或行计数程序的参数解析器,python,python-2.7,Python,Python 2.7,在本例中,如何使代码干燥? 打印的字和行在重复 parser = argparse.ArgumentParser() parser.add_argument('--words', '-w', action='store_true') parser.add_argument('--lines', '-l', action='store_true') parser.add_argument('filename') args = parser.parse_arg
parser = argparse.ArgumentParser()
parser.add_argument('--words', '-w', action='store_true')
parser.add_argument('--lines', '-l', action='store_true')
parser.add_argument('filename')
args = parser.parse_args()
if args.words:
print "Words in a file: {}" .format(print_words(args.filename))
elif args.lines:
print "Lines in a file: {}" .format(print_lines(args.filename))
else:
print "Words in a file: {}" .format(print_words(args.filename))
print "Lines in a file: {}" .format(print_lines(args.filename))
我想通过添加一个新函数并将函数调用放在else语句中
def print_all(filename, args):
for a in read_file(filename):
if a in args:
print "All word counts :", a
我尝试了print_all函数,在else语句中添加了函数调用
def print_all(filename, args):
for a in read_file(filename):
if a in args:
print "All word counts :", a
当我使用print_all函数运行程序时,我得到:
Namaspacewords=False,filename='someFile.txt',lines=False
您的标志有点误导,如果您希望打印,只需将标志设置为true即可
if args.words:
print "Words in a file: {}" .format(print_words(args.filename))
if args.lines:
print "Lines in a file: {}" .format(print_lines(args.filename))
添加一个简单的附加条件以在两个标志都为false时返回true,并删除elif应该可以实现您想要的功能:
if args.words or not arg.lines:
print "Words in a file: {}" .format(print_words(args.filename))
if args.lines or not arg.words:
print "Lines in a file: {}" .format(print_lines(args.filename))
为了扩展到多个条件,你可能想看看这个帖子我建议一个除湿器。如果这是你认为可以改进的工作代码,请考虑@ MorganThrapp:BooMy:这是一个工作代码,我不想改进它看起来不错。如果我有更多的if语句,我将如何编写这段代码?还有5个