كيفية طباعة المقارنة بين سلسلتين متعدد الأسطر في شكل فرق موحد؟

StackOverflow https://stackoverflow.com/questions/845276

  •  20-08-2019
  •  | 
  •  

سؤال

هل تعرف أي مكتبة من شأنها أن تساعد تفعل ذلك؟

وأود أن كتابة دالة الذي يطبع الخلافات بين سلسلتين متعدد الأسطر في شكل فرق موحد. شيء من هذا القبيل:

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
هل كانت مفيدة؟

المحلول

وهذه هي الطريقة I حلها:

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)

نصائح أخرى

هل لديك نظرة على المدمج في بيثون وحدة difflib ؟ ننظر لها أن هذا href="http://docs.python.org/library/difflib.html#differ-example"

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top