简体   繁体   中英

python - parse text between two strings and write each match to separate files

I would like to parse block of text between two strings and send each match to separate file.


I want parse each block of text between "start" and "end" strings and send each match into a separate file. 我想解析“开始”和“结束”字符串之间的每个文本块,并将每个匹配项发送到单独的文件中。

start
2
3
4
end ---> first block of text to name1.txt
dsfsfsd
start
1
2
3
end ----> second block of text to name2.txt
dfdsfsd
sdfsdfsd
sfsdfs

How can I achieve that please? Any advice please?

okay I'm a little unsure about what exactly you're wanting but I think this may be close...

You want to take your matches, whatever they are and find out how to write those strings to a unique file...

You are wanting to put some commands in a loop that will repeat until some criteria is met (ie there are no more matches): Maybe this:

def matchfound(str1, str2)
    #You would return the text that you want to write to the file so put your matching code here....
    #If there is no match remaining, return False

counter=1
while 1:
    x=matchfound(var1,var2)
    if x:
        f=open('Name'+str(counter)+'.txt', 'w')
        f.write(x)
        f.close()
        counter+=1
    else:
        break

If this isn't exactly what you are wanting post a snippit of your code so I could get a better look at what you're trying to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM