Python查找相似单词的方法

yipeiwu_com6年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

对Python 3.2 迭代器的next函数实例讲解

在python中,使用iter函数可以获得有序聚合类型的迭代器,我个人将迭代器理解为带有next指针的单向链表,获取到的迭代器为链表的表头,表头内容为空,next指针指向有序聚合类型的第...

Python实现好友全头像的拼接实例(推荐)

Python实现好友全头像的拼接实例(推荐)

微信好友全头像 话不多说,直接上代码 import itchat import math import PIL.Image as Image import os itchat.a...

django允许外部访问的实例讲解

1、关闭防火墙 service iptables stop 2、设置django 开开启django时,使用0.0.0.0:xxxx,作为ip和端口例如: python ma...

Python中的类与对象之描述符详解

描述符(Descriptors)是Python语言中一个深奥但却重要的一部分。它们广泛应用于Python语言的内核,熟练掌握描述符将会为Python程序员的工具箱添加一个额外的技巧。为了...

python基础 range的用法解析

range基本用法: range:顾头不顾尾 range(10)--返回0-9的数字 ey: for i in range(10): print(i) result:0...