Python利用difflib比较字符串

2023-01-31 02:01:33 python 字符串 利用

#!/usr/bin/python
# -*- coding:utf-8 -*-

import difflib

file1 = file("my.txt","r")
file2 = file("new.txt","r")

temp1_context = file1.read()
temp2_context = file2.read()

file1_context = temp1_context.splitlines()
file2_context = temp2_context.splitlines()

diff = difflib.Differ().compare(file1_context,file2_context)

print "\n".join(list(diff))

------------------------------------------------

my.txt:

hack hack hack hack hack

new.txt:

h4ck h4ck h4ck h4ck h4ck

---------------------the result-----------------

- hack
?  ^

+ h4ck
?  ^

- hack
?  ^

+ h4ck
?  ^

- hack
?  ^

+ h4ck
?  ^

- hack
?  ^

+ h4ck
?  ^

- hack
?  ^

+ h4ck

相关文章