[Python] 두개의 문자열 비교하는 방법 : 같음, 다름, 관계 연산 이해하기에서 문자열을 비교하는 다양한 방법을 알아 보았다. 이제 우리는 더 긴 텍스트 조각을 살펴보고 정확한 차이점을 집어내기 위한 단계를 밟고 있다. 이 포스트에서는 파이썬의 difflib 모듈을 활용하여 상당량의 텍스트를 분석하고 비교하는 과정을 안내할 것이며, 복잡한 데이터 비교를 다루는 데 있어 매우 멋진 도구가 될 것이다.
SequenceMatcher를 활용한 문자열 비교
difflib 모듈의 SequenceMatcher 클래스는 두 문자열을 비교하고 그 사이의 유사도 비율을 확인할 수 있다.
from difflib import SequenceMatcher
string1 = "The sun rises in the east\nA stitch in time saves nine\nAll that glitters is not gold"
string2 = "The sun sets in the west\nA stitch in time saves nine\nAll that shines is not gold\n"
s = SequenceMatcher(None, string1, string2)
similarity_ratio = s.ratio()
print(similarity_ratio) # 출력: 0.9146341463414634
이 코드 조각은 두 문자열을 비교하고 유사도 비율을 얻는 방법을 보여주며, 텍스트 간의 미세한 차이를 신속하게 파악하는 편리한 방법이다.
Differ를 활용한 텍스트 줄 단위 비교
difflib 모듈의 Differ 클래스는 더 큰 텍스트 문서를 줄 단위로 비교할 수 있다.
from difflib import Differ
string1 = "The sun rises in the east\nA stitch in time saves nine\nAll that glitters is not gold"
string2 = "The sun sets in the west\nA stitch in time saves nine\nAll that shines is not gold\n"
text1 = string1.split('\n')
text2 = string2.split('\n')
d = Differ()
diff = d.compare(text1, text2)
print('\n'.join(diff))
출력
- The sun rises in the east
? -- -
+ The sun sets in the west
? + +
A stitch in time saves nine
- All that glitters is not gold
? ^^ ^^ -
+ All that shines is not gold
? ^^ ^
주어진 코드 조각에서, difflib 모듈의 Differ 클래스는 text1과 text2라는 두 문자열 리스트를 비교하는 데 사용된다. 코드의 출력은 두 리스트 간의 차이점을 강조하며, 각 차이의 성격을 지시하는 특정 기호를 사용한다.
-로 시작하는 줄은text1에 있고text2에 없는 요소를 나타낸다.+로 시작하는 줄은text2에 있고text1에 없는 요소를 나타낸다.- 시작 부분에 기호가 없는 줄은 동일한 요소를 나타낸다.
?로 시작하는 줄은 줄 내의 변화를 특정 위치에서 나타내며, 변화가 발생한 곳을 강조하기 위해 다른 문자를 사용한다.
제공된 출력을 분석해 보자:
The sun rises/sets line:
-줄은 "The sun rises in the east"가text1에 있고text2에 없음을 나타낸다.+줄은 "The sun sets in the west"가text2에 있고text1에 없음을 나타낸다.?줄은 정확히 변화한 문자를 지정한다.동일한 줄: "A stitch in time saves nine"는
text1과text2모두에서 동일하므로 시작 부분에 기호가 없다.The glitters/shines line: 첫 번째 줄과 비슷하게,
-,+,?줄은 "All that glitters is not gold"가text1에서 "All that shines is not gold"로text2에서 대체되었음을 보여주며, 특정 변화를 강조한다.
FAQs
difflib으로 이진 파일을 비교할 수 있나요? 아니요,
difflib모듈은 텍스트 줄의 시퀀스를 비교하기 위한 것이다.difflib은 파이썬의 모든 버전에서 사용할 수 있나요?
difflib모듈은 버전 2.1부터 파이썬 표준 라이브러리에서 사용할 수 있다.difflib으로 HTML 파일을 어떻게 비교하나요?
difflib모듈의HtmlDiff클래스를 사용하여 HTML 양옆비교 표를 생성할 수 있다.비교 결과의 출력을 사용자 정의할 수 있나요? 네,
Differ와 같은 클래스는 비교가 수행되는 방식과 출력이 생성되는 방식을 사용자 정의하는 옵션을 제공한다.두 개의 큰 텍스트 간의 변화를 빠르게 파악할 수 있는 방법이 있나요? 네,
difflib.get_opcodes()메소드를 사용하여 변화 블록에 대한 정보를 얻을 수 있으며, 큰 텍스트에 유용할 수 있다.