Python searches for similar words, and python searches for words

Source: Internet
Author: User

Python searches for similar words, and python searches for words

This example describes how to search for similar words in Python. Share it with you for your reference. The specific analysis is as follows:

Problem:

Let's give you a word a. If another word B can be obtained by exchanging the letter order in the word, B is defined as the brother word of. Now, you can enter a word in a dictionary to find out how many brothers the word has.

The Python code is as follows:

from itertools import tee,izipfrom collections import defaultdictdef pairwise(iterable):  a, b = tee(iterable)  for elem in b:    break  return izip(a, b)buf_array=[]buf_no={}key_from_id=0def add_to_buf(word):  global key_from_id,buf_array  if len(word)==1:    pass    #TODO  for pos,pair in enumerate(pairwise(word)):    if len(buf_array)<pos+1:      buf_array.append(defaultdict(set))    pos_dict=buf_array[pos]    key=list(pair)    key.sort()    key="".join(key)    if key not in buf_no:      buf_no[key]=key_from_id      key_from_id+=1    key=buf_no[key]    pos_dict[key].add(word)def find_in_buf(word):  global key_from_id,buf_array  if len(word)==1:    pass    #TODO  exist = []  for pos,pair in enumerate(pairwise(word)):    if len(buf_array)<pos+1:      return      pos_dict=buf_array[pos]    key=list(pair)    key.sort()    key="".join(key)    if key not in buf_no:      continue    key=buf_no[key]    if key not in pos_dict:      continue    exist.append(pos_dict[key])  count_dict=defaultdict(int)  for i_set in exist:    for i in i_set:      count_dict[i]+=1  result=[]  min_match = len(word)-3  for k,v in count_dict.iteritems():    if v>=min_match:      result.append(k)  return resultadd_to_buf("1234")add_to_buf("ABCD")add_to_buf("CABD")print find_in_buf("ACBD")

I hope 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.