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连接mysql数据库示例(做增删改操作)

一、相关代码数据库配置类 MysqlDBConn.py 复制代码 代码如下:#encoding=utf-8'''Created on 2012-11-12Mysql Conn连接类'''...

Python正则表达式实现简易计算器功能示例

本文实例讲述了Python正则表达式实现简易计算器功能。分享给大家供大家参考,具体如下: 需求:使用正则表达式完成一个简易计算器。 功能:能够计算简单的表达式。 如:1*2*((1+...

浅析Python中else语句块的使用技巧

浅析Python中else语句块的使用技巧

学过C/C++的都知道,else语句是和if语句搭配使用的,但是在Python中,else语句更像是作为一个模块,不仅仅可以和if语句搭配,还可以和循环语句,异常处理语句搭配使用。 下面...

Python实现TCP/IP协议下的端口转发及重定向示例

Python实现TCP/IP协议下的端口转发及重定向示例

首先,我们用webpy写一个简单的网站,监听8080端口,返回“Hello, EverET.org”的页面。 然后我们使用我们的forwarding.py,在80端口和8080端口中间建...

我们为什么要减少Python中循环的使用

我们为什么要减少Python中循环的使用

前言 Python 提供给我们多种编码方式。 在某种程度上,这相当具有包容性。 来自于任何语言的人都可以编写 Python。 然而,学习写一门语言和以最优的方式写一门语言是两件不同...