2011-04-13 41 views
0

我一直在嘗試編寫此代碼的不同方式,但無法通過此操作。目前該程序將一直運行到write_names(list)函數並創建文件,打印功能將打印排序列表。該程序拒絕獲取search_names()函數的用戶輸入,但它會打印我要求的任何內容。即使打印函數正在打印列表,但在Python中讀取文件錯誤

調試亮點:while index < len(list)並且在調試I \ O中只聲明「讀取文件錯誤」。希望有人知道我做錯了什麼。

'# Abstract:  This program creates a list of names. The list is printed, 
'#    sorted, printed again, written to file, and searched. 
'#============================================================================= 

'#define the main function 

def main(): 

    #try: 
     ##open data file for read 
     #infile = open('names.txt', 'r') 

    #call get_names function 
    list = get_names() 

    #call print function 
    print_names(list) 

    #sort list 
    list.sort() 

    #print sorted list 
    print_names(list) 

    #write sorted list to new file 
    write_names(list) 

    #allow user to search list 
    search_names(list) 



def get_names(): 

    try: 
     infile = open('names.txt', 'r') 
     #read file contents into a list 
     list = infile.readlines() 
     #close file 
     infile.close() 
     #strip \n from each element 
     index = 0 
     while index < len(list): 
      list[index] = list[index].rstrip('\n') 
      index += 1 
     return list 
    except IOError: 
     print 'Read file error' 

def print_names(list): 

    #print header 
    print '******************' 
    #print list line by line 
    index = 0 
    while index < len(list): 
     print list[index] 
     index += 1 
    return 

def write_names(list): 

    #open file for writing 
    outfile = open('sortedNames.txt', 'w') 
    #write the list to the file 
    for item in list: 
     outfile.write(str(item) + '\n') 
    #close file 
    outfile.close() 

def search_names(list): 

    #set user test variable 
    again = 'Y' 
    while again.upper == 'Y': 
     #get search from user 
     search = raw_input('Enter a name to search for: ') 
     #open list for search 
     if search in list: 
      try: 
       item_index = list.index(search) 
       print search, 'found.', item_index 
      except ValueError: 
       print search, 'not found.' 



main() 
' 

在此先感謝!

+3

我建議不要使用「list」,因爲它是一個內置函數。 – aukaost 2011-04-13 23:42:27

回答

1

你的問題是upper是一個函數,你不是在調用它。您在search_names()while應改爲:

while again.upper() == 'Y': 
0

代替:

#strip \n from each element 
index = 0 
while index < len(list): 
    list[index] = list[index].rstrip('\n') 
    index += 1 
return list 

只是使用這個列表理解:

lines = infile.readlines() 
infile.close() 

return [ line.strip() for line in lines ] 

編輯:

它看起來像您使用的是索引和一個while循環可以使用一個for環路。

相反的:

while index < len(list): 
    print list[index] 
    index += 1 

使用:

# using name_list instead of list 
    for name in name_list: 
     print name 

也,你search_names()函數如下缺陷:

def search_names(list): 

    #set user test variable 
    again = 'Y' 
    while again.upper == 'Y': 
     #get search from user 
     search = raw_input('Enter a name to search for: ') 
     #open list for search 
     if search in list: 
      try: 
       item_index = list.index(search) 
       print search, 'found.', item_index 
      except ValueError: 
       print search, 'not found.' 

永遠不會退出(又從不重新分配)。嘗試:

def search_names(names_list): 
    again = 'Y' 
    while again.upper() == 'Y': 
     s_name = raw_input('Enter a name to search for: ') 
     if s_name in names_list: 
      print s_name, 'found.', names_list.index(s_name) 
     else: 
      print search, 'not found.' 
     again = raw_input('Search for another name (Y|N)?: ') 

或:

def search_names(names_list): 
    again = 'Y' 
    while again == 'Y': 
     s_name = raw_input('Enter a name to search for: ') 
     try: 
      idx = names_list.index(s_name) 
      print s_name, 'found.', idx 
     except ValueError: 
      print search, 'not found.' 
     again = raw_input('Search for another name (Y|N)?: ').upper() 

這帶來了的時候捕捉異常VS使用if語句的問題:

msdn

的方法你選擇取決於你期望事件發生的頻率如何。 如果事件確實例外,並且 是錯誤(例如意外的 文件結束),則使用異常處理 更好,因爲在正常情況下執行的代碼少於 。如果 事件經常發生,使用 編程方法檢查 錯誤會更好。在這種情況下,如果發生異常,則例外將會花費更長的時間處理。

0
  1. 評論開始#,不'# - 你在做你的頭一個文檔字符串的所有其他行。

  2. 您正在使用索引遍歷列表,效率低下 - 只是迭代列表項。

  3. 調用變量list是不好的,因爲它阻止您訪問list()數據類型。

  4. 使用with是開放的().. close()方法更可靠的替代

  5. again.upper是一個函數參考 - 你必須通話的功能,即again.upper()

  6. 你永遠不會改變again的值 - 這將是一個無限循環!

  7. 您測試if search in list但後來做了try..except塊,如果它是不列表(即你正在測試爲同一故障兩次)這隻會失敗。

# 
# Operate on a list of names 
# 

def load_names(fname): 
    try: 
     with open(fname, 'r') as inf: 
      return [line.strip() for line in inf] 
    except IOError: 
     print "Error reading file '{0}'".format(fname) 
     return [] 

def print_names(namelist): 
    print '******************' 
    print '\n'.join(namelist) 

def write_names(namelist, fname): 
    with open(fname, 'w') as outf: 
     outf.write('\n'.join(namelist)) 

def search_names(namelist): 
    while True: 
     lookfor = raw_input('Enter a name to search for (or nothing to quit): ').strip() 
     if lookfor: 
      try: 
       ind = namelist.index(lookfor) 
       print("{0} found.".format(lookfor)) 
      except ValueError: 
       print("{0} not found.".format(lookfor)) 
     else: 
      break 

def main(): 
    namelist = load_names('names.txt') 
    print_names(namelist) 
    namelist.sort() 
    print_names(namelist) 
    write_names(namelist, 'sorted_names.txt') 
    search_names(namelist) 

if __name__=="__main__": 
    main()