如何实现读取File1字符串与File2对比并弹出匹配结果告警窗口
跨平台Python实现方案
- 无需提前知晓两个文件的行数,自动适配任意大小的输入文件
- 用集合存储File2内容,匹配效率远高于普通逐行比对
- 依赖Python自带的
tkinter库实现弹窗,无需额外安装第三方包
import tkinter as tk from tkinter import messagebox def get_file_lines(file_path): """读取文件所有行,自动去除首尾空白、过滤空行""" with open(file_path, 'r', encoding='utf-8') as f: return {line.strip() for line in f if line.strip()} if __name__ == "__main__": # 此处可修改为你的实际文件路径 file1_path = "File1.txt" file2_path = "File2.txt" # 先读取File2全部内容存为集合,加快匹配速度 file2_content = get_file_lines(file2_path) matched_strings = [] # 逐行读取File1进行匹配 with open(file1_path, 'r', encoding='utf-8') as f: for line in f: s = line.strip() if s and s in file2_content: matched_strings.append(s) # 初始化tkinter,隐藏主窗口只显示弹窗 root = tk.Tk() root.withdraw() if matched_strings: msg = f"共匹配到{len(matched_strings)}个结果:\n" + "\n".join(matched_strings) else: msg = "未找到任何匹配的字符串" messagebox.showinfo("匹配结果", msg)
使用说明
- 把代码里的
file1_path和file2_path修改为你实际的文件路径即可运行 - 如果文件用的是非UTF-8编码,修改
open函数里的encoding参数即可,比如中文Windows系统的GBK编码填gbk
内容的提问来源于stack exchange,提问作者Fatima
相关产品推荐
相关产品推荐

