2016-11-30 81 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

我将更新后的部分添加到原始帖子中。原谅我,我对编码很陌生。 –

相关问题