使用用户输入id从txt文件中查找标题并将其添加到列表中



我有一个包含以下信息的txt文件:

  • 545524——Python基础课程——https://img-c.udemycdn.com/course/100x100/647442_5c1f.jpg--Outsourcing开发工作:学习我的成熟系统来雇佣自由开发者
  • 另一行具有相同的格式但不同的信息(可能有相同的id)并继续....

在第1行,Python基础是课程名称。如果用户输入id为545524,我如何打印课程标题Python基础?它基本上是根据给定的输入id打印课程的整个标题。我试着使用以下命令,但是卡住了:

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 

我需要打印基于该id的所有标题。最后将它们添加到列表中。任何帮助都是感激的

Kemmisch在这里是正确的,您可以在---上拆分整个字符串并将每个单独的元素分配给它自己的变量

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)

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

编辑


现在如果你想搜索一个特定的ID,你可以使用if语句。下面的示例使用相同的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)

Provide an ID to search for: 12345
--------------------
12345
Not Python foundation
Ofcourse
https://some.url/here
This is something else

最新更新