Python查找相似单词的方法

yipeiwu_com5年前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调用Matplotlib绘制分布点图

python调用Matplotlib绘制分布点图

Python调用Matplotlib代码绘制分布点,供大家参考,具体内容如下 绘制点图的目的 Matplotlib简介 代码 截图 1.绘制点图的目的 我们实验...

Python进程间通信Queue消息队列用法分析

本文实例讲述了Python进程间通信Queue消息队列用法。分享给大家供大家参考,具体如下: 进程间通信-Queue Process之间有时需要通信,操作系统提供了很多机制来实现进程间的...

从零学python系列之教你如何根据图片生成字符画

从零学python系列之教你如何根据图片生成字符画

说下思路吧: 原图->灰度->根据像素亮度-映射到指定的字符序列中->输出。字符越多,字符变化稠密。效果会更好。如果根据灰度图的像素亮度范围制作字符画,效果会更好。如果...

python线程的几种创建方式详解

Python3 线程中常用的两个模块为: _thread threading(推荐使用) 使用Thread类创建 import threading from time...

Python Requests安装与简单运用

requests是python的一个HTTP客户端库,跟urllib,urllib2类似,那为什么要用requests而不用urllib2呢?官方文档中是这样说明的: python的标...