Python method for keyword matching using BF algorithm

Source: Internet
Author: User
In this paper, we describe the method of Python matching by BF algorithm. Share to everyone for your reference. The implementation method is as follows:

The code is as follows:

#!/usr/bin/python
#-*-Coding:utf-8
# filename BF
Import time
"""
T= "A big apple,this is a big apple,this are a big apple,this is 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 (direction), that is, the vector, so that each article of the word and its frequency constitutes an i-dimensional space map, the similarity of two documents is the proximity of two spatial graphs. Assuming that the article has only two dimensions, then the space map can be drawn in a plane Cartesian coordinate system, the reader can imagine two only two words of the article drawing to understand. "
p= "Readers"
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-word comparison, if the corresponding bit matching, then the next comparison; if not the same, p moves 1 bits to the right, starting from the 1th bit of p to start the comparison again.

Algorithm features: The overall direction of movement: can be considered in a fixed case, p sliding from left to right; when matching comparison, from the leftmost bit of P start to the right bit and the corresponding bit in the T string comparison. The sliding distance of P is 1, which causes the BF algorithm to match less efficiently (compared to other algorithms such as: BM,KMP, sliding without jumping).

The algorithm has a time complexity of O (len (t) *len (p)) and a spatial complexity of O (len (t) +len (p))

Hopefully this article will help you with Python programming.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    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.