2

试图学习如何使用 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()
4

1 回答 1

2

您应该使用OptionParser.add_option()... add_option_group()is not doing what you think it does...这是一个完整的示例,本着您所追求的精神...注意,它--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

于 2011-10-12T02:18:59.537 回答