'Find title from txt file using user input id and add them to a list
I have a txt file with the following info:
- 545524---Python foundation---Course---https://img-c.udemycdn.com/course/100x100/647442_5c1f.jpg---Outsourcing Development Work: Learn My Proven System To Hire Freelance Developers
- Another line with the same format but different info(might have the same id)and continue....
Here on line 1, Python foundation is the course title. If a user has input id 545524 how do I print out course title Python foundation? It's basically printing the whole title of a course based on the given input id. I tried using following but got stuck:
input = ''
with open(r"sample.txt") as data:
read_data = data.read()
id_search = re.findall(r'regex, read_data)
title_search = re.findall(r'regex', read_data)
for id_input in id_search:
if input in id_input:
#Then I got stuck
I need to print all the titles based on that id. and finally add them to a list. Any help is appreciated
Solution 1:[1]
Kemmisch is on the money here, you can just split the whole string on the --- and assign each separate element to it's own variable
somefile.txt
545524---Python foundation---Course---https://img-c.udemycdn.com/course/100x100/647442_5c1f.jpg---Outsourcing Development Work: Learn My Proven System To Hire Freelance Developers
12345---Not Python foundation---Ofcourse---https://some.url/here---This is something else
main.py
with open('somefile.txt') as infile:
data = infile.read().splitlines() # os agnostic, and removes end of lines characters
for line in data:
idnr, title, dunno_what_this_is, url, description = line.split('---')
print('--------------------')
print(idnr)
print(title)
print(dunno_what_this_is)
print(url)
print(description)
output
--------------------
545524
Python foundation
Course
https://img-c.udemycdn.com/course/100x100/647442_5c1f.jpg
Outsourcing Development Work: Learn My Proven System To Hire Freelance Developers
--------------------
12345
Not Python foundation
Ofcourse
https://some.url/here
This is something else
EDIT
Now if you want to search for a specific ID you can just use an if statement. Sample below uses the same somefile.txt.
id_input = input("Provide an ID to search for: ")
with open('somefile.txt') as infile:
data = infile.read().splitlines() # os agnostic, and removes end of lines characters
for line in data:
idnr, title, dunno_what_this_is, url, description = line.split('---')
if idnr == id_input:
print('--------------------')
print(idnr)
print(title)
print(dunno_what_this_is)
print(url)
print(description)
output
Provide an ID to search for: 12345
--------------------
12345
Not Python foundation
Ofcourse
https://some.url/here
This is something else
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
