Python:在文本文件中搜索字符串并显示匹配的行

标签 python python-3.x list search

我现在有这个程序,它允许用户从类别中进行选择(从文件中提取)。然后它将打印该文本文件中的大学或人员。

我接下来想要在代码中执行的操作是让用户从该文件中搜索特定字符串,它将显示具有该匹配字符串的大学和人员。它可以是该文件中的整个单词或字符串的一部分。

我需要有关搜索给定字符串或字符串的一部分并显示匹配类别(大学和人物)的帮助。

示例:

搜索:

输出:

大学:加州大学洛杉矶分校姓名:John Kelly

大学:孟菲斯大学姓名:Taylor Johnson

这是我当前的文本文件:

"UniversityName","ContactName"
"UCLA","John Kelly"
"UofFlorida","Mary Elizabeth"
"U of Memphis","Taylor Johnson"
"Harvard","Robert Fax"

这是我到目前为止对代码所做的事情:

def load_data(file_name):
    university_data=[]
    with open(file_name,'r') as rd_file:
        for line in rd_file.readlines():
            line=line.strip().split(',')
            T = line[0],line[1]
            university_data.append(T)
    return university_data

def main():
    filename='List.txt'
    university_data = load_data(filename)
    print('[1] University\n[2] Contact Name\n[3] Exit\n[4] Search')
    while True:

        choice=input('Enter choice 1/2/3? ')
        if choice=='1':
            for university in university_data:
                print(university[0])
        elif choice=='2':
            for university in university_data:
                print(university[1])
        elif choice =='3':
            print('Thank You')
            break
        elif choice =='4':
            print("Search Section Here")
        else:
            print('Invalid selection')

main()

最佳答案

根据您的数据:

university_data = [["UniversityName","ContactName"],
["UCLA","John Kelly"],
["UofFlorida","Mary Elizabeth"],
["U of Memphis","Taylor Johnson"],
["Harvard","Robert Fax"]]

使用str.join:

def search(key, data):
    for l in data:
        if key in ''.join(l):
            print('University: %s Name: %s' % (l[0], l[1]))
search('ohn', university_data)
# University: UCLA Name: John Kelly
# University: U of Memphis Name: Taylor Johnson

关于Python:在文本文件中搜索字符串并显示匹配的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55037113/

相关文章:

python - 查找列表中连续项目的索引

python - 在 Python 中从列表列表到文件

python - pandas - 与相同类别的列连接变成对象

python - 如何从python终端播放音频文件

javascript - 如何在 django 模板标签中传递 Javascript 变量

python - 如何在 PyQt5 QColorDialog 中显示 alpha channel

python - 如何访问Python列表中从最后到第一个的所有列表元素

python - ASP.NET 成员(member)资格的开源替代方案

python - 向二叉搜索树添加一个元素

python - 如何使用发布数据重定向(Django)