我正在尝试读取特定字符串的python文件,并将字符串出现的索引存储在另一个变量中。
例如:
student_id("1234", "1345", "1342")
class_enrolled("biology", "math", english)
# Insert 50 lines of code to do something
student_id("2134", "2345", "2342")
class_enrolled("biology", "math", english)
# Insert 50 lines of code to do something
student_id("3134", "3345", "3342")
class_enrolled("biology", "math", english)
总体目标是确定每个学生ID开始的索引,以及每个“class_enrolled”索引的开始位置,以便我只能将学生ID存储在列表中。
我尝试解决方案:
file = open('This is my file').read()
end_of_id_list = []
for ch in file:
start_list = file.find('student_id')
end_list = file.find('class_enrolled')
if end_list != -1:
end_of_id_list.append(end_list)
这给了我一个无限循环。有没有人对更好的方法有任何建议?如果我的解释不清楚我想要做什么,我会提前道歉。
发布于 2018-09-19 10:30:21
如果最终你只需要学生证,而不关心它们发生在哪里,你可以这样做:
import re
with open('yourfile','r') as f:
txt=f.read()
re.findall("student_id\(.*?\)",txt)
https://stackoverflow.com/questions/-100002682
复制相似问题