python文本比較庫difflib使用示例
python的包很豐富, difflib是用來做文本比較的,下面是一個使用例子:
import difflib lines1 = ''' dog cat bird buffalo gophers hound horse '''.strip().splitlines() lines2 = ''' cat dog bird buffalo gopher horse mouse '''.strip().splitlines() # Changes: # swapped positions of cat and dog # changed gophers to gopher # removed hound # added mouse for line in difflib.unified_diff(lines1, lines2, fromfile='file1', tofile='file2', lineterm=''): print line
輸出內容如下:
Outputs the following: --- file1 +++ file2 @@ -1,7 +1,7 @@ +cat dog -cat bird buffalo -gophers -hound +gopher horse +mouse
這個類庫也可以用來比較兩個文本文件。
本文由用戶 cgdf 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!