代码之家  ›  专栏  ›  技术社区  ›  Andrea Francia

如何以统一的diff格式打印两个多行字符串的比较?

  •  19
  • Andrea Francia  · 技术社区  · 17 年前

    我将编写一个函数,以统一的diff格式打印两个多行字符串之间的差异。诸如此类:

    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
    
    2 回复  |  直到 17 年前
        1
  •  28
  •   Andrea Francia    17 年前

    我就是这样解决的:

    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)
    
        2
  •  25
  •   Nadia Alramli    17 年前

    您看过内置的python模块了吗 difflib ? 看看这个 example

    推荐文章