[英]How to print the comparison of two multiline strings in unified diff format?
您知道有任何圖書館可以幫助您做到這一點嗎?
我將編寫一個函數,以統一的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
這是我解決的方法:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.