如何找出1.0.txt中存在但Master.txt中缺失的提交消息?
问题描述
我有两个文件1.0.txt和Master.txt,需要获取所有存在于1.0.txt但在Master.txt中缺失的提交列表。提交格式示例:
19175c1 Correct the logic by Jacob · 2 days ago 8.4.0.109
我只需要比较其中的提交消息部分:
Correct the logic
如果该提交消息未出现在Master.txt中,就输出它。
我写了一段Python代码,但逻辑错误,会输出所有行:
import json count = 0 with open("1.0.txt") as release, open("Master.txt") as master: for message in release: for line in master: splitting_line = message[8:].split(' by', 1) if not splitting_line[0] in line: count += 1 print(f"{count}. {line}")
代码错误分析
- 文件指针耗尽问题:
Master.txt的文件对象在第一次循环后就会读取到末尾,后续遍历1.0.txt的行时,master文件已经没有内容可以读取,导致逻辑完全失效。 - 判断逻辑颠倒:原代码是检查当前
release的消息是否不在当前master行中就输出,但这不是我们要的——我们需要判断release的消息是否完全不存在于所有master的消息中,再输出。 - 冗余模块导入:代码里导入了
json模块但完全没用到,属于冗余代码。
修正后的代码
先把Master.txt里所有的提交消息提取出来存到集合里(集合查找效率更高),再遍历1.0.txt的每一行,提取消息后检查是否不在集合中,符合条件就输出:
def extract_commit_message(line): # 提取提交消息:从第8位开始,到' by'之前的部分,去除首尾空格 try: msg_part = line[8:].split(' by', 1)[0].strip() return msg_part except IndexError: # 处理格式不符合的行,返回空字符串跳过 return "" # 先读取Master.txt的所有提交消息到集合 master_messages = set() with open("Master.txt", encoding="utf-8") as master_file: for line in master_file: msg = extract_commit_message(line) if msg: master_messages.add(msg) # 遍历1.0.txt,找出不在master中的消息 count = 0 with open("1.0.txt", encoding="utf-8") as release_file: for line in release_file: release_msg = extract_commit_message(line) if release_msg and release_msg not in master_messages: count += 1 print(f"{count}. {release_msg}")
代码说明
- 提取函数封装:用
extract_commit_message统一处理提交行的消息提取,加入异常处理避免格式异常的行导致报错。 - 集合存储优化:用集合存储master的消息,集合的成员检查操作
in比列表快很多,文件越大优势越明显。 - 分阶段读取文件:先缓存master的所有消息,再遍历release文件逐一对比,彻底解决文件指针耗尽的问题,逻辑更清晰。
内容的提问来源于stack exchange,提问作者art
相关产品推荐
相关产品推荐

