20

それを行うのに役立つライブラリを知っていますか?

統一された差分形式で 2 つの複数行文字列の違いを出力する関数を作成します。そんな感じ:

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

使用例は次のとおりです。

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)

これにより、次のように出力されます。

--- 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
4

2 に答える 2

28

これが私が解決した方法です:

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)
于 2009-05-10T14:25:22.553 に答える
25

組み込みの python モジュールdifflibを見ましたか? この例を見てください

于 2009-05-10T12:54:51.893 に答える