首先,那个正则表达式搞砸了\d+ 表示“一个或多个数字”,那么为什么要将它们中的三个链接在一起呢?此外,您需要对这种模式使用“原始字符串”,因为\ 被视为转义字符,因此您的模式无法正确构建。你想把它改成re.search(r'"status":\d+}}', d)。
其次,如果您的块中有两个换行符,您的d.split() 行可能会选择错误的\n。
你甚至不需要正则表达式,好的 ol' Python 字符串搜索/切片足以确保你得到正确的分隔符:
logs = [] # store for our individual entries
buffer = [] # buffer for our partial chunks
for chunk in r.iter_content(chunk_size=25): # read chunk-by-chunk...
eoe = chunk.find("}}\n") # seek the guaranteed event delimiter
while eoe != -1: # a potential delimiter found, let's dig deeper...
value_index = chunk.rfind(":", 0, eoe) # find the first column before it
if eoe-1 >= value_index >= eoe-4: # woo hoo, there are 1-3 characters between
try: # lets see if it's a digit...
status_value = int(chunk[value_index+1:eoe]) # omg, we're getting there...
if chunk[value_index-8:value_index] == '"status"': # ding, ding, a match!
buffer.append(chunk[:eoe+2]) # buffer everything up to the delimiter
logs.append("".join(buffer)) # flatten the buffer and write it to logs
chunk = chunk[eoe + 3:] # remove everything before the delimiter
eoe = 0 # reset search position
buffer = [] # reset our buffer
except (ValueError, TypeError): # close but no cigar, ignore
pass # let it slide...
eoe = chunk.find("}}\n", eoe + 1) # maybe there is another delimiter in the chunk...
buffer.append(chunk) # add the current chunk to buffer
if buffer and buffer[0] != "": # there is still some data in the buffer
logs.append("".join(buffer)) # add it, even if not complete...
# Do whatever you want with the `logs` list...
它看起来很复杂,但如果您逐行阅读它实际上很容易,并且您还必须使用正则表达式匹配来处理其中的一些复杂性(重叠匹配等)(考虑到同一块中潜在的多个事件分隔符)。