optparse和字符串

2024-10-01 15:45:26 发布

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

尝试学习如何使用outparse。所以现在的情况是,我想我的设置是正确的,它只是如何设置我的选项有点。。。把我弄糊涂了。基本上我只想检查我的文件名,看看是否有特定的字符串。在

例如:

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

我想让它返回类似。。。在

^{pr2}$

这是我到目前为止所拥有的,我只是不知道如何正确地设置它。抱歉问了些愚蠢的问题: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()

Tags: the字符串pyparserifmain文件名选项
1条回答
网友
1楼 · 发布于 2024-10-01 15:45:26

您应该使用OptionParser.add_option()。。。add_option_group()没有做你认为的那样。。。这是一个完全符合你所追求的精神的例子。。。注意, all依赖于逗号分隔值。。。这使得它更简单,而不是使用空格分隔(这将需要为 all引用选项值)。在

还要注意,您应该显式地检查options.search_and和{},而不是检查{}的长度

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

相关问题 更多 >

    热门问题