The example of this article is about Python using the BF algorithm to achieve keyword matching method. Share to everyone for your reference. The implementation methods are as follows:
Copy Code code as follows:
#!/usr/bin/python
#-*-Coding:utf-8
# filename BF
Import time
"""
T= "This are a big apple,this are a big apple,this are a big apple,this are a Big Apple."
p= "Apple"
"""
T= "Why is it called a vector space model?" In fact, we can think of each word as a dimension, and the frequency of the word as its value (there is a direction), that is, vector, so that each article of the word and its frequency constitutes an i-dimensional space diagram, two of the similarity of the document is the proximity of two space graphs. If the article is only two dimensions, then the space map can be drawn in a plane rectangular coordinate system, the reader can imagine two only two words of the article drawing to understand. "
p= "Reader"
I=0
Count=0
Start=time.time ()
while (I <=len (t)-len (p)):
J=0
while (T[i]==p[j]):
I=i+1
J=j+1
If J==len (p):
Break
Elif (J==len (p)-1):
Count=count+1
Else
I=i+1
J=0
Print Count
Print Time.time ()-start
Algorithm idea: The target string T and the pattern string p are compared to each other, if corresponding bit match, then carries on the next comparison; if not the same, p shifts 1 digits to the right, starting from the 1th digit of p.
Algorithm features: The overall moving direction: it can be considered that in a fixed case, p sliding from left to right, the matching comparison, from the leftmost bit of p to the right and the corresponding bit in the T-string. The sliding distance of P is 1, which leads to the low matching efficiency of the BF algorithm (compared to other algorithms, such as: BM,KMP, sliding without jumps).
The time complexity of the algorithm is O (len (t) *len (p)), and the space complexity is O (len (t) +len (p))
I hope this article will help you with your Python programming.