Skip to main content
 首页 » 编程设计

python之来自 json 响应的解码二进制内容的行数

2025年05月04日11insus

我在下面有一些代码计算解码后的 GitHub 二进制内容中的行数,然后根据文件的更改计数查找百分比更改。这包含在 if/else 语句的循环中的循环中。我现在所做的工作,但它输出拉取请求中每个单独文件的结果。如果返回文件集中的任何结果满足 if 语句中的条件(否则打印没有文件已更改),我想只写一次 if/else,然后继续进行下一组评估。

     found = False 
     for data in repo.pull_request(prs.number).files(): 
         if data.filename.endswith((".png",".jpeg",".gif")): 
             pass 
         else: 
             for files_content in [repo.blob(data.sha)]: 
                 binary_coded_content = io.BytesIO((base64.b64decode(files_content.content))) 
                 tempfile = 'temp' 
                 with open(tempfile,'wb') as f: 
                     f.write(binary_coded_content.read()) 
                 num_lines = sum(1 for line in open(tempfile, encoding='utf8') if line.rstrip()) 
                 if data.changes_count/num_lines > 0.25: 
                     found = True 
                     break 
     if found: 
         print("A file has changed by more than 25%", '\n') 
     else: 
         print("No file has changed by more than 25%", '\n') 

请您参考如下方法:

如果我理解正确的话,您想创建一个found 变量并像这样在循环外测试它

found = False # <---- 
for data in repo.pull_request(prs.number).files(): 
    if data.filename.endswith((".png",".jpeg",".gif")): 
        pass 
    else: 
 
        for files_content in [repo.blob(data.sha)]: 
             binary_coded_content = io.BytesIO((base64.b64decode(files_content.content))) 
             tempfile = 'temp' 
             with open(tempfile,'wb') as f: 
                 f.write(binary_coded_content.read()) 
             num_lines = sum(1 for line in open(tempfile, encoding='utf8') if line.rstrip())  
             if data.changes_count/num_lines > 0.25: 
                found = True # <---- 
                break #<--- break inner loop 
        if found: 
            break #<--- break outer loop 
    if found: # after the loop ended, we check if we found something... 
        print("A file has changed by more than 25%") 
    else: 
        print("No file has changed by more than 25%")