Python/Python Programming
[ Python ] difflib 모듈 ( 문자열 비교, 유사도 )
Pydole
2023. 4. 24. 11:42
difflib.SequenceMatcher ( 유사도 )
from difflib import SequenceMatcher
def similar(a, b):
return round(float(SequenceMatcher(None, a, b).ratio()),2) * 100
print(similar('서울시 강남구','서울시 영등포구 '))
-----------------------------------------------------------------------
62.0
difflib.context_diff ( 문자열 목록 비교 )
samplefile_1.txt | samplefile_2.txt |
1 파이썬 2 python 3 iz 4 beautiful |
1 파이선 2 python 3 is 4 beautiful 5 6 diff |
from difflib import context_diff
with open('samplefile_1.txt', 'r') as f1:
with open('samplefile_2.txt', 'r') as f2:
diff = context_diff(f1.readlines(), f2.readlines(), fromfile='f1', tofile='f2')
for line in diff:
print(line)
------------------------------------------------------------------------------------------
*** f1
--- f2
***************
*** 1,4 ****
! 파이썬
python
! iz
beautiful
--- 1,6 ----
! 파이선 # file1과 file2 1 line 다른점
python
! is # file1과 file2 3 line 다른점
beautiful
+
# file2만 있는 내용
+ diff # file2만 있는 내용