【问题标题】:Python 3: search text file with user input?Python 3:使用用户输入搜索文本文件?
【发布时间】:2017-04-14 04:31:54
【问题描述】:

在我的程序的一部分中,我想将一个排序后的名称列表从一个文本文件传递给一个函数,该函数要求用户输入一个名称,然后指示输入的名称是否在列表中找到.如果找到名字,它的位置(即索引)也会被打印出来。

该文件只有 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.')

【问题讨论】:

    标签: python file search text input


    【解决方案1】:

    首先,您只想打开一次正在搜索​​的文件。您可以使用 .readlines() 将文件中的所有行加载到列表中,此函数在列表中为每一行返回一个字符串。然后你可以在每一行中搜索用户字符串

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

    【讨论】:

    • 我尝试使用“try/except ValueError”,但现在它只会打印 ValueError 或“未找到”打印语句
    • @twenty-3 需要查看新的和更新的代码。
    • 我将更新后的文章添加到原始帖子中。原谅我,我对编码很陌生。
    猜你喜欢
    • 2021-11-23
    • 2013-08-31
    • 2012-03-21
    • 2019-03-21
    • 2013-12-06
    • 1970-01-01
    • 2017-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多