单词计数和/或行计数程序的参数分析器

2024-04-25 00:48:31 发布

您现在位置:Python中文网/ 问答频道 /正文

在这个例子中如何使代码变干? 印刷的字和行是重复的。。在

    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语句中添加了函数调用。在

^{pr2}$

当我使用print_all函数运行程序时,我得到:

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


Tags: store函数inaddformatparserargsaction
2条回答

添加一个简单的附加条件以在两个标志均为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))

要扩展到多个条件,您可能需要查看这篇文章python argparse set behaviour when no arguments provided

你的旗子有点误导性,如果你想把它打印出来,只需让它是真的。

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

相关问题 更多 >