2009-05-10 4 views
13

그 일을하는데 도움이되는 도서관을 알고 있습니까?두 개의 여러 줄 문자열을 통합 된 diff 형식으로 비교하는 방법은 무엇입니까?

두 개의 여러 줄 사이의 차이점을 통합 된 diff 형식으로 인쇄하는 함수를 작성했습니다. 뭐 그런이 그 같은 인쇄해야

string1=""" 
Usage: trash-empty [days] 

Purge trashed files. 

Options: 
    --version show program's version number and exit 
    -h, --help show this help message and exit 
""" 

string2=""" 
Usage: trash-empty [days] 

Empty the trash can. 

Options: 
    --version show program's version number and exit 
    -h, --help show this help message and exit 

Report bugs to http://code.google.com/p/trash-cli/issues 
""" 

print_differences(string1, string2) 

:

def print_differences(string1, string2): 
    """ 
    Prints the comparison of string1 to string2 as unified diff format. 
    """ 
    ??? 

사용 예는 다음과 같다

--- string1 
+++ string2 
@@ -1,6 +1,6 @@ 
Usage: trash-empty [days] 

-Purge trashed files. 
+Empty the trash can. 

Options: 
    --version show program's version number and exit 

답변

18

이것은 내가 해결 방법입니다 :

def _unidiff_output(expected, actual): 
    """ 
    Helper function. Returns a string containing the unified diff of two multiline strings. 
    """ 

    import difflib 
    expected=expected.splitlines(1) 
    actual=actual.splitlines(1) 

    diff=difflib.unified_diff(expected, actual) 

    return ''.join(diff) 
18

당신이 한 번 봐 있었나요을 내장 파이썬 모듈 difflib? 보라 것은이 example