This article mainly introduces the KMP implementation method of the Python string matching algorithm. The example analyzes Python's skills related to string operations, which has some reference value, for more information about the Python String Matching Algorithm KMP, see the example in this article. Share it with you for your reference. The details are as follows:
#! /Usr/bin/env python # encoding: utf8def next (pattern): p_len = len (pattern) pos = [-1] * p_lenj =-1for I in range (1, p_len): while j>-1 and pattern [j + 1]! = Pattern [I]: j = pos [j] if pattern [j + 1] = pattern [I]: j = j + 1pos [I] = jreturn posdef kmp (ss, pattern): pos = next (pattern) ss_len = len (ss) pattern_len = len (pattern) j =-1for I in range (ss_len): while j>-1 and pattern [j + 1]! = Ss [I]: j = pos [j] if pattern [j + 1] = ss [I]: j = j + 1if j = pattern_len-1: print 'matched @: % s' % str (i-pattern_len + 1) j = pos [j] kmp (u 'shanghai tap water from Shanghai', u 'shanghai ')
I hope this article will help you with Python programming.