用于字数和/或行计数程序的参数解析器

时间:2015-09-14 17:09:09

标签: 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_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语句中。

我尝试使用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函数运行程序时,我得到:

  

Namaspace(words = False,filename ='someFile.txt',lines = False)

2 个答案:

答案 0 :(得分:3)

你的旗帜有点误导,如果你想要打印它,只需将旗帜设为真。

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))

答案 1 :(得分:1)

添加一个简单的附加条件,当两个标志都为false并且删除elif时返回true应该做你想要的:

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))

要扩展到多个条件,您可以查看此帖子python argparse set behaviour when no arguments provided