2013-04-06 35 views
0
while True: 
    try: 
     OpenFile=raw_input(str("Please enter a file name: ")) 
     infile=open(OpenFile,"r") 
     contents=infile.readlines() 
     infile.close() 

     user_input = raw_input(str("Enter A=<animal> for animal search or B=<where lives?> for place of living search: \n")) 
     if user_input.startswith("A="): 
      def find_animal(user_input,column): 
       return next(("\t".join(line) for line in contents 
          if line[column-1]==user_input),None) 
      find_animal(user_input[1:]) 
      print str((find_animal(user_input[1:], "WHO?"))) #"Who?" is the name of the first column. 

     else: 
      print "Unknown option!" 


    except IOError: 
     print "File with this name does not exist!" 

1.輸入動物名稱。製表符分隔的列文件中的Python搜索功能

2.程序在第一列中搜索具有此特定名稱的行。

3.Program在第一列中打印具有此名稱的行。

我的功能似乎無法在這裏正常工作。你能幫我找到錯誤嗎?謝謝!

編輯

 def ask_for_filename(): 
     filename=str(raw_input("Please enter file name: ")) 
     return filename 

     def read_data(filename): 
     contents=open(filename,"r") 
     data=contents.read() 
     return data 

     def column_matches(line, substring, which_column): 
     for line in data: 
      if column_matches(line, substring, 0): 
       print line 
+0

有沒有必要調用一個字符串的'str()'。 – poke 2013-04-07 19:46:42

回答

0

的代碼大塊難以閱讀和調試,嘗試拆分代碼成更小的功能,例如像這樣:

def ask_for_filename(): 
    #left as an exercise 
    return filename 

def read_data(filename): 
    #left as an exercise 
    return data 

def column_matches(line, substring, which_column): 
    #left as an exercise 

def show_by_name(name, data): 
    for line in data: 
     if column_matches(line, name, 0): 
      print line 

def do_search(data): 
    propmt = "Enter A=<animal> for animal search or B=<where lives?> for place of living search: \n" 
    user_input = raw_input(prompt) 
    if user_input.startswith('A='): 
     show_by_name(user_input[2:], data) 

# main program 

filename = ask_for_filename() 
data = read_data(filename) 
while True: 
    do_search(data) 

測試和調試這些功能分開直到你確定它們正常工作。然後編寫並測試主程序。

column_matches()應該返回true,如果line中的某列(which_column)等於substring。例如,column_matches("foo\tbar\tbaz", "bar", 1)True。爲了實現這一目標

  • 由分隔符分割線 - 這給了我們值的列表
  • 獲取列表
  • 與substing比較它的第n個元素
  • 返回true,如果他們是相等的,否則爲false

全部放在一起:

def column_matches(line, substring, which_column): 
    delimiter = '\t' 
    columns = line.split(delimiter) 
    value = columns[which_column] 
    if value == substring: 
     return True 
    else: 
     return False 

或以更簡潔和「pythonic」形式:

def column_matches(line, substring, which_column): 
    return line.split('\t')[which_column] == substring 
+0

謝謝你的幫助。我試圖完成這些練習,但我無法真正理解我在第三個函數中必須做什麼[請參閱編輯]。難道你不能解釋我在那裏要做什麼嗎? – meowtwo 2013-04-07 19:46:29

+0

@AlButter:我添加了更多細節。 – georg 2013-04-07 20:37:32

+0

感謝您的幫助,現在我完全瞭解如何正確使用功能。順便說一句,你可以請建議任何良好的Python課程,一步一步的解釋? – meowtwo 2013-04-08 16:59:17

相關問題