简体   繁体   中英

search a word in a file and print only the text betwen two separator

I'm trying to code a searching fonction that gonna read a file and print name from it, without any other of the information on that line, I found out how to print the complete line only yet..

title = input("\n Enter a movie name: ")
        with open("Data_Film") as f:
            for line in f:
                if title in line:
                    print(line)

here what look like the file it must search in :

1;Avatar;Science Fiction;3;2;3.99
2;Little Frog;Horror;2;3;3.99
...

so if I search a title, I would want it to check only from the first ";" to the second ";" as that where the movie name is and print it.

Thanks, hope my question was clear enought, english is not my native language.

Assuming your data file always will be in that format, and the title will always be after the second ';', you can use the native split function using the semicolon as the delimiter. This splits the line at the semicolons into an array, and the title is the second element.

title = input("\n Enter a movie name: ")
    with open("Data_Film") as f:
        for line in f:
            if title in line:
                print(line.split(';')[1])

Try this one:

title = input("\n Enter a movie name: ")

with open("Data_Film") as f:
    for line in f:
        name = line.split(';')[1]
        if title == name:
            print(name)

This fixes the indentation and searches only between the first and the second ';'.

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