Trie树 不解析,  本园很多博文有提到。

直接上代码:

#coding:utf-8
'''
create on 2013-07-30
@author :HuangYanQiang
'''
LETTER_NUM=27;#组成单词的字母个数,26个字母+'-' #Trie 结构体
class Node:
def __init__(self, is_word=False):
global LETTER_NUM;
self.is_word = is_word;#是不是单词结束节点
self.prefix_count = 0;#这个前缀的单词个数
self.children = [None for child in range(LETTER_NUM)]; #Trie 结构体
class Trie:
def __init__(self):
self.head = Node();
###插入新单词
def insert(self, word):
current = self.head;
count = 0 ; for letter in word:
if (letter == '-'):
int_letter=LETTER_NUM-1;
else:
int_letter = ord(letter)-ord('a');
if(current.children[int_letter] is None):
current.children[int_letter] = Node();
current = current.children[int_letter];
count += 1;
current.prefix_count = count;
else:
current = current.children[int_letter];
current.prefix_count += 1;
current.is_word = True;
###查询单词是否存在
def search(self, word):
current = self.head;
int_letter = 0;
for letter in word:
if (letter == '-'):
int_letter=LETTER_NUM-1;
else:
int_letter = ord(letter)-ord('a'); if (current.children[int_letter] is None):
#print "int_letter = " + str(int_letter);
return False;
else:
current = current.children[int_letter];
return current.is_word;
###根据字母前缀输出所有的单词
def output(self,strPrefix):
if(strPrefix is None or strPrefix == ""):
print ("please tell me prefix letter.");
currentNode = self.head;
int_letter = 0;
for letter in strPrefix:
if (letter == '-'):
int_letter=LETTER_NUM-1;
else:
int_letter = ord(letter)-ord('a');
currentNode = currentNode.children[int_letter]; if(currentNode is not None):
if(currentNode.is_word):
print (strPrefix+"; ");
else:
return; for i in range(LETTER_NUM):
if(currentNode.children[i] is not None):
self.output(strPrefix+chr(i+ord('a'))); ################# ###读取单词列表文本构造Trie结构
class BuildTrie: def __init__(self):
self.trie = Trie();
for line in file("EnglishDict.txt"):
line = line.lower();#全部换成小写
line = line.replace('\r','').replace('\n','');#去掉结束符
isword = True;
int_letter = 0;
str_letter="abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for letter in line:
if(letter not in str_letter ):
isword = False;
break;
if(isword == False):
print (line + ", it is not a word");
continue;
else:
self.trie.insert(line); if __name__=="__main__":
import doctest
doctest.testmod(); # t = Trie();
# t.insert("apple");
# t.insert("abc");
# t.insert("abandon");
# t.insert("bride");
# t.insert("bridegroom");
# t.insert("good");
# t.output("b"); bt = BuildTrie();
t = bt.trie
t.output("z"); print t.search("apple");
print t.search("fff");
print t.search("good");
print("a num:"+str(t.head.children[0].prefix_count));
print("ab num:"+str(t.head.children[0].children[1].prefix_count));
print("b num:"+str(t.head.children[1].prefix_count));

我的第一个python代码实践:Trie树的更多相关文章

  1. kNN算法基本原理与Python代码实践

    kNN是一种常见的监督学习方法.工作机制简单:给定测试样本,基于某种距离度量找出训练集中与其最靠近的k各训练样本,然后基于这k个“邻居”的信息来进行预测,通常,在分类任务中可使用“投票法”,即选择这k ...

  2. 一个python代码练习

    需求: 写一个用户登录窗口 验证输入的用户名和密码,若正确打印欢迎信息,输入错误三次则加入锁定名单. 锁定名单要持久化存储 # *-* coding:utf-8 *-* # Auth: wangxz ...

  3. 第一个python代码

    # -*- coding:utf-8 -*- user = raw_input("请输入用户名") passwd = raw_input("请输入密码") if ...

  4. 15行python代码,帮你理解令牌桶算法

    本文转载自: http://www.tuicool.com/articles/aEBNRnU   在网络中传输数据时,为了防止网络拥塞,需限制流出网络的流量,使流量以比较均匀的速度向外发送,令牌桶算法 ...

  5. if __name__== "__main__" 的意思(作用)python代码复用

    if __name__== "__main__" 的意思(作用)python代码复用 转自:大步's Blog  http://www.dabu.info/if-__-name__ ...

  6. 第一个python程序

    一个python程序的两种执行方式: 1.第一种方式是通过python解释器: cmd->python->进入python解释器->编写python代码->回车. 2.第二种方 ...

  7. beamer中插入c代码,python代码的经验

    下面是插入的scala代码,它与python在某些语法上类似,所在在https://github.com/olivierverdier/python-latex-highlighting下载了一个py ...

  8. 如何使用 Pylint 来规范 Python 代码风格

    如何使用 Pylint 来规范 Python 代码风格 转载自https://www.ibm.com/developerworks/cn/linux/l-cn-pylint/   Pylint 是什么 ...

  9. 使用Pylint规范你的Python代码

    Pylint是一个Python代码风格的检查工具,功能上类似于pychecker,默认用PEP8作为代码风格标准,它所提供的功能包括:检查代码行的长度,检查变量命名是否符合规范,检查声明的接口是否被真 ...

随机推荐

  1. java编程思想第四版中net.mindview.util包

    把 net那个包 放入到你编写的项目同一个文件夹下(与src文件夹平级的那个),然后刷新一下工程即可

  2. 正则表达式 之 C#后台应用

    正则表达式在.Net就是用字符串表示,这个字符串格式比较特殊,无论多么特殊,在C#语言看来都是普通的字符串,具体什么含义由Regex类内部进行语法分析. Regex 类 存在于 System.Text ...

  3. svn学习总结

    安装svn subversion服务参考博客http://huihai.iteye.com/blog/1985238 一:svn版本管理的作用 a:备份程序   项目开发过程中,防止不可控因素造成的资 ...

  4. vsftpd给root设置访问权限

    1:Linux下安装vsftpd之后,默认的配置是匿名用户可以登录,匿名帐户有两个:用户名:anonymous密码:空 用户名:ftp密码:ftp 2:如果要用匿名进行上传删除等操作需要配置其它参数. ...

  5. 关于Git中的一些常用的命令

    深入了解git的checkout命令 检出命令(git checkout)是Git最常用的命令之一,同时也是一个很危险的命令. 因为这条命令会重写工作区.检出命令的用法如下: 用法一: git che ...

  6. angularjs的一些优化小技巧

    尽可能少调用 ng-repeat ng-repeat默认会创建很多监听器,所以在数据量很大的时候,这个非常消耗页面性能,我觉的只有在当需要经常更新数据列表的时候才需要用ng-repeat,要不然放那么 ...

  7. 【转】Oracle - 数据库的实例、表空间、用户、表之间关系

    [转]Oracle - 数据库的实例.表空间.用户.表之间关系 完整的Oracle数据库通常由两部分组成:Oracle数据库和数据库实例. 1) 数据库是一系列物理文件的集合(数据文件,控制文件,联机 ...

  8. linux命令 common 文件比较

    比较已经排序的文件 comm [options] file1 file2 comm将逐行比较已经排序的两个文件.显示结果包括3列: 第1列为只在file1中找到的行;第2列为只在file2中找到的行; ...

  9. 【html】【7】基础布局初探

    当了解了上面的文章有一定基础后,开始尝试初步基础布局,可能不美观,但是要开始有布局框架思想 基础代码: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML ...

  10. CSS3的几个标签速记1

    border-radius:CSS3圆角   语法:border-radius:25px;     椭圆边角:语法-border-radius:xx%;或者15px/100px; box-shadow ...