在下面的教程中,我們將了解 Python 編程語言中的 difflib
模塊。我們將討論這個模塊的功能以及一些基於它的類的例子。
所以,讓我們開始吧。
理解 Python difflib
模塊
Difflib 是 Python 編程語言中的內置模塊,由不同的簡單函數和類組成,允許用戶比較數據集。該模塊以人類可以閱讀的格式提供這些序列比較的輸出,使用差值來更有效地顯示差異。
difflib
模塊通常用於比較字符串的順序。但是我們也可以用它來比較其他數據類型,只要它們是可哈希的。我們知道,如果一個對象的哈希值在它的生命周期內沒有改變,那麼它就是可哈希的。
Python difflib
模塊中最常用的類是 different 類和序列匹配器類。還有一些其他的幫助類和函數可以幫助更特殊的操作。讓我們在接下來的章節中了解其中的一些功能。
理解序列匹配器類
讓我們首先從 difflib
模塊的一個相當不言自明的方法開始: SequenceMatcher 。SequenceMatcher 方法將比較兩個提供的字符串,並返回表示兩個字符串之間相似性的數據。讓我們藉助比()對象來試試這個方法。該對象將以十進制格式返回比較數據。相同的示例如下所示:
示例:
# importing the difflib library and SequenceMatcher class
import difflib
from difflib import SequenceMatcher
# defining the strings
str_1 = "Welcome to Javatpoint"
str_2 = "Welcome to Python tutorial"
# using the SequenceMatcher() function
my_seq = SequenceMatcher(a = str_1, b = str_2)
# printing the result
print("First String:", str_1)
print("Second String:", str_2)
print("Sequence Matched:", my_seq.ratio())
輸出:
First String: Welcome to Javatpoint
Second String: Welcome to Python tutorial
Sequence Matched: 0.5106382978723404
說明:
在上面的代碼片段中,我們首先導入了 difflib 模塊以及 SequenceMatcher 類。然後我們定義了兩個字符串值,我們將在該類的幫助下進行比較。之後,我們創建了一個新的變量,它用兩個參數封裝了 SequenceMatcher 類,分別是 a 和 b 。而該方法實際上接受三個參數:無,a ,b。
為了讓方法確認這兩個字符串,我們必須將字符串的每個值分配給方法的變量, SquenceMatcher(a = str_1,b = str_2)** 。
一旦定義了每個需要的變量,並且序列匹配器至少提供了兩個參數,我們現在就可以藉助於前面提到的比率()對象來打印該值。該對象將確定兩個字符串中相同字符的比例,輸出以十進制形式返回。就像這樣,我們比較了兩個簡單的字符串,並收到了關於它們相似性的輸出。
注意:ratio()對象是與序列匹配器類相關聯的幾個對象之一。您可以查看 Python 的官方文檔,了解更多這些對象,以便對序列執行不同的操作。
理解不同的類別
different類被認為是 SquenceMatcher 的反義詞;它接收文本行並找出字符串之間的差異。但是差異類在三角洲的利用上是特別的,這使得人類發現差異的效率和可讀性更高。
例如,當在兩個字符串之間的比較中向第二個字符串插入新字符時,在接收到額外字符的行之前會彈出一個“ + ”。
正如我們可能已經猜到的,刪除第一個字符串中的一些可見字符將導致第二行文本之前出現“ – ”。
如果兩個序列中有一行相同,將返回“,”如果缺少一行,那麼“?’會出現。此外,我們還可以使用屬性,如比率(),我們在前面的示例中討論過。
讓我們考慮下面的例子來理解不同類的工作原理。
示例:
# importing the difflib module and Differ class
import difflib
from difflib import Differ
# defining the strings
str_1 = "They would like to order a soft drink"
str_2 = "They would like to order a corn pizza"
# using the splitlines() function
lines_str1 = str_1.splitlines()
lines_str2 = str_2.splitlines()
# using the Differ() and compare() function
dif = difflib.Differ()
my_diff = dif.compare(lines_str1, lines_str2)
# printing the results
print("First String:", str_1)
print("Second String:", str_2)
print("Difference between the Strings")
print('\n'.join(my_diff))
輸出:
First String: They would like to order a soft drink
Second String: They would like to order a corn pizza
Difference between the Strings
- They would like to order a soft drink
? ^ ^^ ^^ ^^
+ They would like to order a corn pizza
? ^ ^^ ^ ^^^
說明:
在上面的代碼片段中,我們已經導入了 difflib 模塊和different類。然後,我們定義了要比較的兩個字符串。然後,我們在兩個字符串上調用了分裂線()函數。
語法:
lines_str1 = str_1.splitlines()
lines_str2 = str_2.splitlines()
這個函數允許我們按每行而不是按每個字符來比較字符串。
一旦我們定義了一個由different類組成的變量,我們就創建了另一個包含different和 compare() 對象的變量,該對象接受兩個字符串作為參數。
語法:
my_diff = dif.compare(lines_str1, lines_str2)
我們調用 print() 函數,並將 my_diff 變量與一行 enter 連接起來,這樣輸出就可以用一種更易讀的方法進行格式化。
理解 get_close_matches 方法
difflib 模塊作為 get_close_matches 方法提供了另一個簡單而強大的工具。這個方法聽起來很像:一個接受參數並返回與目標字符串最接近的匹配的工具。在偽代碼中,函數以下列方式運行:
語法:
get_close_matches(target_word, list_of_possibilities, n = res_limit, cutoff)
我們可以觀察到上面的語法, get_close_matches() 方法接受四個參數;但是,它只需要第一個兩個就可以返回輸出。
第一個參數是必須針對的詞;我們希望該方法返回相似性。第二個參數可以是指向字符串數組的變量或術語數組。第三個參數允許用戶定義返回的輸出數量的限制。最後一個參數決定了兩個單詞之間的相似度需要多少才能作為輸出返回。
單用前兩個參數,該函數將基於 0.6 (在 0 – 1 範圍內)的默認截止值和 3** 的默認結果限制返回輸出。讓我們考慮下面的例子來理解這個函數的工作原理。
示例:
# importing the difflib module and get_close_matches method
import difflib
from difflib import get_close_matches
# using the get_close_matches method
my_list = get_close_matches('mas', ['master', 'mask', 'duck', 'cow', 'mass', 'massive', 'python', 'butter'])
# printing the list
print("Matching words:", my_list)
輸出:
Matching words: ['mass', 'mask', 'master']
說明:
在上面的代碼片段中,我們已經導入了 difflib 模塊和 get_close_matches 方法。然後,我們使用了 get_close_matches() 方法,列出了一些在性質上有些相似的項目。一旦我們執行該程序,該函數將只返回其中有相似字母的三個單詞,即使有第四個項目類似於單詞“MAS”:“massive”。現在,讓我們嘗試在以下示例中定義一個結果限制和一個截止:
示例:
# importing the difflib module and get_close_matches method
import difflib
from difflib import get_close_matches
# using the get_close_matches method
my_list = get_close_matches(
'mas',
['master', 'mask', 'duck', 'cow',
'mass', 'massive', 'python', 'butter'],
n = 4,
cutoff = 0.6
)
# printing the list
print("Matching words:", my_list)
輸出:
Matching words: ['mass', 'mask', 'master', 'massive']
說明:
在上面的代碼片段中,我們得到了四個至少與單詞“ mas 相似 60% 的結果。截止相當於原來的我們剛剛定義的默認值相同, 0.6 。但是,我們可以更改此參數,使結果或多或少更嚴格。越靠近 1 ,約束越嚴格。
理解統一的 _diff & context_diff 類
difflib 中有兩個類的工作方式相同: unified_diff 和 context_diff 。兩者之間唯一的主要區別是結果。
unified_diff 類接受兩個數據字符串,然後返回從第一個字符串插入或刪除的每個單詞。
為了更好地理解,讓我們考慮下面的例子。
示例:
# importing the required modules
import sys
import difflib
from difflib import unified_diff
# defining the string variables
str_1 = ['Mark\n', 'Henry\n', 'Richard\n', 'Stella\n', 'Robin\n', 'Employees\n']
str_2 = ['Arthur\n', 'Joseph\n', 'Stacey\n', 'Harry\n', 'Emma\n', 'Employees\n']
# using the unified_diff() function
sys.stdout.writelines(unified_diff(str_1, str_2))
輸出:
---
+++
@@ -1,6 +1,6 @@
-Mark
-Henry
-Richard
-Stella
-Robin
+Arthur
+Joseph
+Stacey
+Harry
+Emma
Employees
說明:
在上面的代碼片段中,我們已經導入了所需的模塊,並定義了兩個存儲一些單詞的變量。然後,我們使用 unified_diff()函數從第一個變量中刪除單詞,並將第二個變量中的單詞添加到第一個變量中。因此,我們可以觀察到 unified_diff 返回刪除的前綴為 – 的單詞,返回添加的前綴為 + 的單詞。最後一個單詞, Employees ,在兩個字符串中都沒有前綴。
context_diff 類的工作方式與 unified_diff 相似。但是,它不會顯示從原始字符串中插入和刪除的內容,而是通過返回前綴為“!”的已更改行來返回已更改的行。
讓我們考慮下面的例子來理解這個類的工作。
示例:
# importing the required modules
import sys
import difflib
from difflib import context_diff
# defining the string variables
str_1 = ['Mark\n', 'Henry\n', 'Richard\n', 'Stella\n', 'Robin\n', 'Employees\n']
str_2 = ['Arthur\n', 'Joseph\n', 'Stacey\n', 'Harry\n', 'Emma\n', 'Employees\n']
# using the context_diff() function
sys.stdout.writelines(context_diff(str_1, str_2))
輸出:
***
---
***************
*** 1,6 ****
! Mark
! Henry
! Richard
! Stella
! Robin
Employees
--- 1,6 ----
! Arthur
! Joseph
! Stacey
! Harry
! Emma
Employees
說明:
在上面的例子中,我們使用了 context_diff 來移除和添加第一個字符串中的單詞。同樣的結果可以觀察到,因為被改變的單詞用“!”來描述前綴。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/243451.html