简体   繁体   中英

Python: Search for string on a text file and display matching rows

I have this program right now where it allows users to choose from a category(pulling from the file). Then it will print the University or people from that text file.

What I want to do next on my code is for users to search for a specific string from that file and it will display both the University and People that have that matching string. It can be the whole word or part of the string from that file.

I need help on searching for a given string or part of a string and display matching categories (University and People).

Example:

search: ohn

output:

University: UCLA Name: J ohn Kelly

University: U of Memphis Name: Taylor J ohn son

Here is my current text file:

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

This is what I've done so far with my code:

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()

Given your data:

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

Use 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

Similar to the previous answer by @Chris , in case you want to ignore the upper or lowercase of the search word, you can add lower() in the search function.

def search(key, mydata):
    for l in mydata:
        if key in (''.join(l)).lower():
            print('University: %s Name: %s' % (l[0], l[1])) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM