Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

python - I need to filter contents of my text file

I have a text file that I want to loop through, slice some contents, and store in a separate list. The text file contains:

blu sre
before we start
start the process
blah blah
blah blha
end the process
blah b?ah
start the process
blah blah
blah blha
end the process
start the process
blah blah
end the process
blah

I want to catch all text between 'start the process' and 'end the process' and store in a new list so that each line of the list will contain every text between start the process and end the process. The desired new list should be like this

list[0] start the process  
blah blah  
blah blha  
end the process   
list[1] start the process  
blah blah  
blah blha  
end the process   
list[2] start the process  
blah blah  
end the process  

Here is the code I prepared. I don't why its not giving me the required result.

list = []
text = 'start the process'
text2 = 'end the process'
for pattern in range (len(file)):
    if text in file[pattern]:
        x = pattern
    if text2 in file[pattern]:
        y = pattern
    list[i]= file[x:y]
 i = i+1
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Regex is built for that.

import re

part = re.compile(r"start the process(.*?)end the process", flags=re.DOTALL)
wirh open("my_file.text", "r") as file:
    data = file.read()

results = list(part.findall(data))

EDIT update code based on @Xosrov comment


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...