Python實現字串匹配演算法執行個體代碼

來源:互聯網
上載者:User
這篇文章主要介紹了Python實現字串匹配演算法程式碼範例,涉及字串匹配存在的問題,蠻力法字串匹配,Horspool演算法,具有一定參考價值,需要的朋友可以瞭解下。

字串匹配存在的問題

Python中在一個長字串中尋找子串是否存在可以用兩種方法:一是str的find()函數,find()函數只返回子串匹配到的起始位置,若沒有,則返回-1;二是re模組的findall函數,可以返回所有匹配到的子串。

但是如果用findall函數時需要注意字串中存在的特殊字元。

蠻力法字串匹配:

將模式對準文本的前m(模式長度)個字元,然後從左至右匹配每一對對應的字元,直到全部匹配或遇到一個不匹配的字元。後一種情況下,模式向右移一位。

代碼如下:

def string_match(string, sub_str):  # 蠻力法字串匹配  for i in range(len(string)-len(sub_str)+1):   index = i  # index指向下一個待比較的字元   for j in range(len(sub_str)):    if string[index] == sub_str[j]:     index += 1    else:     break    if index-i == len(sub_str):     return i  return -1 if __name__ == "__main__":  print(string_match("adbcbdc", "dc"))

最壞情況下,該演算法屬於Θ(nm),事實上,該演算法的平均效率比最差效率好得多。事實上在尋找隨機文本的時候,其屬於線性效率Θ(n)。

Horspool演算法:

Horsepool演算法是Boyer-Moore演算法的簡化版本,這也是一個空間換時間的典型例子。演算法把模式P和文本T的開頭字元對齊,從模式的最後一個字元開始比較,如果嘗試比較失敗了,它把模式向後移。每次嘗試過程中比較是從右至左的。

在蠻力演算法中,模式的每一次移動都是一個字元,Horspool演算法的核心思想是利用空間來換取時間,提升模式比對視窗的移動幅度。與蠻力演算法不同的是,其模式的匹配是從右至左的,通過預先算出每次移動的距離並存於表中。

代碼如下:

__author__ = 'Wang' from collections import defaultdict def shift_table(pattern):  # 產生 Horspool 演算法的移動表  # 當前檢測字元為c,模式長度為m  # 如果當前c不包含在模式的前m-1個字元中,移動模式的長度m  # 其他情況下移動最右邊的的c到模式最後一個字元的距離  table = defaultdict(lambda: len(pattern))  for index in range(0, len(pattern)-1):   table[pattern[index]] = len(pattern) - 1 - index  return table def horspool_match(pattern, text):  # 實現 horspool 字串匹配演算法  # 匹配成功,返回模式在text中的開始部分;否則返回 -1  table = shift_table(pattern)  index = len(pattern) - 1  while index <= len(text) - 1:   print("start matching at", index)   match_count = 0   while match_count < len(pattern) and pattern[len(pattern)-1-match_count] == text[index-match_count]:    match_count += 1   if match_count == len(pattern):    return index-match_count+1   else:    index += table[text[index]]  return -1 if __name__ == "__main__":  print(horspool_match("barber", "jim_saw_me_in_a_barbershopp"))

顯然,Horspool演算法的最差效率屬於屬於Θ(nm)。在尋找隨機文本的時候,其屬於線性效率Θ(n)。雖然效率類型相同,但平均來說,Horspool演算法比蠻力演算法快很多。

以上內容就是Python實現字串匹配演算法執行個體代碼,希望能協助到大家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.