optparse 和字符串

2 投票
1 回答
4475 浏览
提问于 2025-04-17 04:08

我正在学习如何使用outparse。现在的情况是,我觉得我的设置应该没问题,但设置选项的方式让我有点困惑。基本上,我只是想检查我的文件名,看看里面是否包含特定的字符串。

举个例子:

    python script.py -f filename.txt -a hello simple

我希望它能返回类似这样的结果...

    Reading filename.txt....
    The word, Hello, was found at: Line 10
    The word, simple, was found at: Line 15

这是我目前的进展,但我不知道该怎么正确设置。抱歉问了一些傻问题 :P。提前谢谢你们。

以下是我目前的代码:

    from optparse import OptionParser

    def main():

        usage = "useage: %prog [options] arg1 arg2"
        parser = OptionParser(usage)

        parser.add_option_group("-a", "--all", action="store", type="string", dest="search_and", help="find ALL lines in the file for the word1 AND word2")

        (options, args) = parser.parse_args()

        if len(args) != 1:
            parser.error("not enough number of arguments")

            #Not sure how to set the options...


    if __name__ == "__main__":
        main()

1 个回答

2

你应该使用 OptionParser.add_option() 来添加选项... 而 add_option_group() 并不是你想的那样... 这里有一个完整的例子,符合你的需求... 注意 --all 需要用逗号来分隔值... 这样更简单,而不是用空格分隔(那样的话就需要给 --all 的选项值加上引号)。

另外,注意你应该明确检查 options.search_andoptions.filename,而不是检查 args 的长度。

from optparse import OptionParser

def main():
    usage = "useage: %prog [options]"
    parser = OptionParser(usage)
    parser.add_option("-a", "--all", type="string", dest="search_and", help="find ALL lines in the file for the word1 AND word2")
    parser.add_option("-f", "--file", type="string", dest="filename", help="Name of file")
    (options, args) = parser.parse_args()

    if (options.search_and is None) or (options.filename is None):
        parser.error("not enough number of arguments")

    words = options.search_and.split(',')
    lines = open(options.filename).readlines()
    for idx, line in enumerate(lines):
        for word in words:
            if word.lower() in line.lower():
                print "The word, %s, was found at: Line %s" % (word, idx + 1)

if __name__ == "__main__":
    main()

用你相同的例子,运行脚本时可以这样写... python script.py -f filename.txt -a hello,simple

撰写回答