Python 3.x 从文件读取如何将字符串附加到列表,直到python中的特定标记

Python 3.x 从文件读取如何将字符串附加到列表,直到python中的特定标记,python-3.x,list,Python 3.x,List,我有一个输入文本文件: This file contains information of students who are joining picnic: @@@ bob alice rhea john mary alex roma peter &##& 现在我想在find@@@marker时在一行的列表中追加学生的姓名,并在find&###marker时停止追加。输出应为(使用python): 将re.findall与re.sub一起使用

我有一个输入文本文件:

  This file contains information of students who are joining picnic:
     @@@ bob alice rhea john 
     mary alex roma
     peter &##&
现在我想在find@@@marker时在一行的列表中追加学生的姓名,并在find&###marker时停止追加。输出应为(使用python):


re.findall
re.sub
一起使用:

inp=“”此文件包含参加野餐的学生的信息:
@@@鲍勃·艾丽斯·瑞亚·约翰
玛丽·亚历克斯·罗马
彼得和
output=re.sub(r'\s+','',re.findall(r'@@@s+(.*)\s+&##&',inp,flags=re.DOTALL)[0])
打印(输出)#bob alice rhea john mary alex roma peter
如果需要列表,请使用:

output = re.split(r'\s+', re.findall(r'@@@\s+(.*?)\s+&##&', inp, flags=re.DOTALL)[0])
print(output)
这张照片是:

['bob', 'alice', 'rhea', 'john', 'mary', 'alex', 'roma', 'peter']

你可以用这个方法

txt = """This file contains information of students who are joining picnic:
     @@@ bob alice rhea john 
     mary alex roma
     peter &##&"""
或:

这张照片是:

['bob', 'alice', 'rhea', 'john', 'mary', 'alex', 'roma', 'peter']

感谢您的回答,但对于我从文本文件读取的实际文件,有以下错误。“文件”C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\re.py”,第241行,在findall return\u compile(pattern,flags)中。findall(string)TypeError:expected string或bytes like object“我上面粘贴的代码按原样工作。你的脚本一定做错了什么。如果我也想打印开始标记呢。请你回答好吗?TIA.写下你的意思是哪一部分?输出应该是:@@@bob alice rhea john mary alex roma Peter将其更改为:
ls=txt.split(“:”)[1]。split(&##&”)[0]。split()
它不工作。我在记号笔前也有一些线。
txt = open("./file.txt").read()  

ls = txt.split("@@@")[1].split("&##&")[0].split()
print(ls)
['bob', 'alice', 'rhea', 'john', 'mary', 'alex', 'roma', 'peter']