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. Conclusion

    Conclusion This concludes our brief look at building a simple, but fully functional, Zend Framework ...

  2. Java 之 调用.Net的 WebService 整理

    最近做一个 java 调用 .net 服务的项目,其中 .net做了一个WebService,需要java来调用. 最开始.net的Service代码如下: using System; using S ...

  3. Android四大组件之服务-Service 原理和应用开发详解

    一.Android 服务简介 Service是android 系统中的四大组件之一(Activity.Service.BroadcastReceiver.ContentProvider),它跟Acti ...

  4. JavaScript中的各种宽高以及位置总结

    JavaScript中的各种宽高以及位置总结 在javascript中操作dom节点让其运动的时候,常常会涉及到各种宽高以及位置坐标等概念,如果不能很好地理解这些属性所代表的意义,就不能理解js的运动 ...

  5. zTree默认选中指定节点并执行事件

    var treeObj = $.fn.zTree.getZTreeObj("treeDemo"); var node = treeObj.getNodeByParam(" ...

  6. 关于SWT/JFace的API文档

    在CSDN上下了几个CHM格式的文档,下载的时候要付的分数还挺高,但是下载下来三个都不能用,左边罗列了所有的类和方法.双击按回车右边都没有内容. 真坑爹. >>>>>&g ...

  7. LC-检索

    line void LC(tree T,float cost) { //为找一个答案结点检索T if(T是答案结点) {输出T:return:} E=T: //E-结点 将活结点表初始化为空: ) { ...

  8. [转]Spring数据库读写分离

    数据库的读写分离简单的说是把对数据库的读和写操作分开对应不同的数据库服务器,这样能有效地减轻数据库压力,也能减轻io压力. 主(master)数据库提供写操作,从(slave)数据库提供读操作,其实在 ...

  9. JSON对象和string的相互转换

    JSON.stringify(obj) 将JSON转为字符串. JSON.parse(string) 将字符串转为JSON格式.

  10. 注册Model类

    根据username查找是否存在相同的用户名的方法 自动填充功能填充注册时间字段 如果两次输入的密码一直则写入数据库的方法 userModel.class.php <?php /**** 燕十八 ...