2016-11-30 104 views
-1

我的程序中有一部分內容我想將文本文件中的名稱排序列表傳遞給一個函數,該函數要求用戶輸入名稱,然後指出是否在列表中找到輸入的名稱。如果找到該名稱,則它的位置(即索引)也被打印出來。Python 3:搜索帶有用戶輸入的文本文件?

該文件只有30個名字,但是當第二個函數被執行時,它會在輸入我想要搜索的名稱後顯示:
找不到名稱。
找不到名字。
找到的名稱
找不到名字。
找不到名字。
...等所有30個名字。

下面的代碼:

def main(): 
    infile = open('names.txt', 'r') 
    line = infile.readline() 

    while line !='': 
     line = line.rstrip('\n') 
     print(line) 
     line = infile.readline() 

    print('\nHere are the names sorted:\n') 

    infile = open("names.txt", 'r') 
    names = infile.readlines() 
    names.sort() 

    for line in names: 
     line = line.rstrip('\n') 
     print(line) 
     line = infile.readline() 
     search_file(line) # I don't this this is the correct way to 
          # pass the sorted list of names? 


def search_file(line): 
    search = open('names.txt', 'r') 
    user_search = input('\nSearch for a name(Last, First): ') 
    #item_index = line.index(search) 
    print() 

    with open('names.txt', 'r') as f: 
     for line in f: 
      if user_search in line: 
       print('name found')#, item_index) 
      else: 
       print('name not found.') 

更新的代碼在這裏: 這個時候它總是顯示「未找到」

def search_file(line): 

user_search = input('\nSearch for a name(Last, First): ') 
print() 

try: 
    item_index = line.index(user_search) 
    print(user_search, 'found at index', item_index) 

except ValueError: 
    print('not found.') 

回答

0

那麼首先你只需要打開你正在尋找一個文件時間。您可以使用.readlines()將文件中的所有行加載到列表中。此函數爲每行返回一個列表中的字符串。然後,你可以在每個符合搜索用戶串

for l in lines: 
    if (l.find(userstring)>-1): 
     foundvar=True 
+0

我試圖用「嘗試/除ValueError異常」,但現在它只能打印ValueError異常或「未找到」 print語句 –

+0

@ 23將需要查看新的和更新的代碼。 –

+0

我將更新後的部分添加到原始帖子中。原諒我,我對編碼很陌生。 –