2011-10-12 28 views
2

試圖學習如何使用outparse。所以這裏是情況,我認爲我的設置正確,它的設置只是讓我感到困惑。基本上我只想檢查我的文件名,看看是否有特定的字符串。optparse和字符串

例如:

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

回答

2

您應該使用OptionParser.add_option() ... add_option_group()沒有做什麼你認爲它...這是在你的精神,一個完整的例子」再之後......注意,--all依賴於逗號分隔值......這使得而是採用空間分離(這需要爲--all引用選項值更容易。

還要注意的是,你應該檢查options.search_andoptions.filename明確,而不是ch ecking的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

+0

如果我想添加另一種選擇的劇本?比如,讓我們說...一個能夠找到text1或者text1的人?你認爲這是明智的嗎?如果聲明帶有選項?像if(options.search_and是true):[...]?等等? – inoobdotcom

+0

聽起來不錯。我會試一試。之後我會發布代碼! Python很有趣哈哈。使我能夠快速搜索文件。 :D – inoobdotcom

+0

現在我想起來了,從技術上講,你已經在用現有的例子進行OR搜索...... –