python文本比對


1.說明

文本比對腳本(可比對IP,域名等文本)
set1_ip.txt 為舊文件
set2_ip.txt 為新文件
start_py.bat 為啟動腳本

結果顯示說明

delete:  為新文件里面沒有,但舊文件里面有

add:  為新文件里面有,舊文件里面沒有的

unchanged:  為新舊文件都存在的

2.代碼

新建start_py.bat 批處理文件,寫入以下批處理代碼(當前使用環境是python3.8.0,可根據實際環境更改)

title 文本比對腳本
%cd%\python-3.8.0\python.exe diff_txt.py set1_ip.txt set2_ip.txt
pause

diff_txt.py 比對腳本文件代碼如下:

# -*- coding:UTF-8 -*-
import sys

def diff_content(set1,set2):
    common_set = set1 & set2
    only1_set = set1 - set2
    only2_set = set2 - set1
    print "delete:"
    for j in list(only1_set):
        print j
    print "\n\n"
    print "add:"
    for h in list(only2_set):
        print h
    print "\n\n"
    print "unchanged:"
    for i in list(common_set):
        print i

def read_file(filename):
    content_set = set()
    with open(filename,'r') as f:
        for line in f:
            line= line.replace(" ","").replace('\n','')
            content_set.add(line)
    return content_set

if __name__ == "__main__" :
    set1_file=read_file(sys.argv[1])
    set2_file=read_file(sys.argv[2])
    diff_content(set1_file,set2_file)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM