• home
  • about
  • 全ての投稿
  • ソフトウェア・ハードウェアの設定のまとめ
  • 分析関連のまとめ
  • ヘルスケア関連のまとめ
  • 生涯学習関連のまとめ

python difflib

date: 2023-09-23 excerpt: pythonのdifflibの概要と使い方

tag: difflibpython


pythonのdifflibの概要と使い方

概要

  • gitのdiffのようなものをpythonで行えるもの
  • デフォルトライブラリ

使い方

import difflib

def get_diff(text1, text2):
    d = difflib.Differ()
    diff = list(d.compare(text1.splitlines(), text2.splitlines()))
    return '\n'.join(diff)

text1 = """apple
banana
cherry
date"""

text2 = """apple
berry
cherry
date
elderberry"""

print(get_diff(text1, text2))
"""
  apple
- banana
+ berry
  cherry
  date
+ elderberry
"""

Google Colab

  • python-difflib

参考

  • difflib — Helpers for computing deltas


difflibpython Share Tweet