本文實例講述了Python查找相似單詞的方法。分享給大家供大家參考。具體分析如下:
問題:
給你一個單詞a,如果通過交換單詞中字母的順序可以得到另外的單詞b,那么定義b是a的兄弟單詞。現在給你一個字典,用戶輸入一個單詞,讓你根據字典找出這個單詞有多少個兄弟單詞。
Python代碼如下:
- from itertools import tee,izip
- from collections import defaultdict
- def pairwise(iterable):
- a, b = tee(iterable)
- for elem in b:
- break
- return izip(a, b)
- buf_array=[]
- buf_no={}
- key_from_id=0
- def 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 result
- add_to_buf("1234")
- add_to_buf("ABCD")
- add_to_buf("CABD")
- print find_in_buf("ACBD")
希望本文所述對大家的Python程序設計有所幫助。