Techmaster
Techmaster

Reputation: 41

Print the title from a txt file from the given word

I have a txt file with the following info:

Here on line 1, Python foundation is the course title. If a user has input "foundation" how do I print out Python foundation? It's basically printing the whole title of a course based on the given word. I can use something like:

input_text = 'foundation'
file1 = open("file.txt", "r")
readfile = file1.read()
if input_text in readfile: 
    #This prints only foundation keyword not the whole title 

Upvotes: 2

Views: 742

Answers (3)

AlirezaAsadi
AlirezaAsadi

Reputation: 803

I assume that your input file has multiple lines separated by enters in this format:
<Course-id>---<Course-name>---Course---<Course-image-link>---<Desc>

input_text = 'foundation'
file1 = open('file.txt', 'r')
lines = file1.readlines()
for line in lines:
    book_title_pattern = r'---([\w\d\s_\.,;:()]+)---'
    match = re.search(book_title_pattern, line)
    if match:
        matched_title = match.groups(1)[0]
        if input_text in matched_title:
            print(matched_title)

Upvotes: 2

Abhyuday Vaish
Abhyuday Vaish

Reputation: 2379

You can use regex to match ---Course name--- using ---([a-zA-Z ]+)---. This will give you all the course names. Then you can check for the user_input in each course and print the course name if you find user_input in it.:

import re

user_input = 'foundation'
file1 = open("file.txt", "r")
readfile = file1.read()
course_name = re.findall('---([a-zA-Z ]+)---', readfile)
for course in course_name:
    if user_input in course: #Then check for 'foundation' in course_name
        print(course)

Output:

Python foundation

Upvotes: 0

Adon Bilivit
Adon Bilivit

Reputation: 27043

Get the key value that you're searching for. User input perhaps or we'll hard-code it here for demo' purposes.

Open the file and read one line at a time. Use RE to parse the line looking for a specific pattern. Check that we've actually found a token matching the RE criterion then check if it contains the 'key' value. Print result as appropriate.

import re
key = 'foundation'
with open('input.txt') as infile:
    for line in map(str.strip, infile):
        if (t := re.findall('---([a-zA-Z\s]+)---', line)) and key in t[0]:
            print(t[0])

Upvotes: 0

Related Questions