
在[Python] 比較兩個字符串:理解等於、不等於和關係操作裡,我們探索了比對字串的各種方式。現在,我們更進一步檢視長篇文字,並精確地找出差異所在。本博客文章將引導您運用 Python 的 difflib 模組分析和比較大量的文字,對於處理複雜數據比對的人而言,這是一項無可取代的工具。
difflib 模組的 SequenceMatcher 類別能用來比對兩個字串,並識別它們之間的相似度比例。
from difflib import SequenceMatcher
string1 = "The sun rises in the east\nA stitch in time saves nine\nAll that glitters is not gold"
string2 = "The sun sets in the west\nA stitch in time saves nine\nAll that shines is not gold\n"
s = SequenceMatcher(None, string1, string2)
similarity_ratio = s.ratio()
print(similarity_ratio) # 輸出:0.9146341463414634此程式碼片段演示了如何比對兩個字串並取得相似度比例,這是一個快速識別文字間細微差異的方便方法。
difflib 模組的 Differ 類別讓我們能夠逐行比對較大的文本文件。
from difflib import Differ
text1 = string1.split('\n')
text2 = string2.split('\n')
d = Differ()
diff = d.compare(text1, text2)
print('\n'.join(diff))輸出
- The sun rises in the east
? -- -
+ The sun sets in the west
? + +
A stitch in time saves nine
- All that glitters is not gold
? ^^ ^^ -
+ All that shines is not gold
? ^^ ^
在給定的程式碼片段中,difflib 模組的 Differ 類別被用來比對兩個字串序列,text1 和 text2。代碼的輸出突出了這兩個序列之間的差異,使用特定符號來指示每個差異的性質:
text1 中存在但 text2 中不存在的元素。text2 中存在但 text1 中不存在的元素。讓我們分析所提供的輸出:
text1 中,但不在 text2 中。 「+」行顯示 "The sun sets in the west" 在 text2 中,但不在 text1 中。 「?」行精確指出了已改變的字符。text1 和 text2 中是相同的,因此開頭沒有任何符號。text1 中已被 "All that shines is not gold" 在 text2 中替換,並突出了具體的變化。difflib 模組是用來比對文字行序列的。difflib 模組自 2.1 版開始在 Python 標準庫中提供。difflib 模組的 HtmlDiff 類別生成 HTML 平行比較表。Differ 這樣的類別提供選項來自訂比對的執行方式和輸出的生成方式。difflib.get_opcodes() 方法來獲取有關變化塊的資訊,這對於大型文本可能很有用。| [Python] 通過各種實例深入理解位元運算符 |
|---|
| [Python] 通過各種實例深入理解關係運算符 |
| [Python] 解決 'zsh: command not found: python' 錯誤的方法 |
| [Python] 通過各種實例深入理解賦值運算符 |
| [Python] 通過各種實例深入理解算術運算符 |

CloneCoding
創新從一行代碼開始!