2023年12月6日发(作者:居宝)
基于trie树的具有联想功能的文本编辑器
之前的软件设计与开发实践课程中,自己构思的大作业题目。做的具有核心功能,但是还欠缺边边角角的小功能和持久化数据结构,先放出
来,有机会一点点改。github:
数据结构,使用过程截图以及源代码如下:
#数据结构
**trie树**
trie树相应的介绍点击链接
trie树在python文件中的类型定义
Node定义
#GUI设计界面
首先,用较大的文本文件进行训练,完成trie的树的训练。本文件夹下提供了一个文件作为示例。
在之后的输入会弹出提示框
#!/usr/bin/python
# -*- coding: utf-8 -*-
import PyQt4
from import *
from import *
import
import sys
import pickle
print '===================start======================='
class Node:
def __init__(self):
= None
en = {} # children is of type {char, Node}
= 0
= None
def CMP(a, b):
return -
class Trie:
def __init__(self):
= Node()
= []
self.__OpenCorrect__ = 0
def insert(self, key): # key is of type string
# key should be a low-case string, this must be checked here!
node =
for char in key:
if char not in en:
child = Node()
en[char] = child
= char
= node
node = child
else:
node = en[char]
# = key
+= 1
def search(self, key):
node =
for char in key:
if char not in en:
return None
else:
node = en[char]
return
def display_node(self, node):
if ( != None):
for char in 'abcdefghijklmnopqrstuvwxyz':
if char in en:
y_node(en[char])
return
def fallback(self, node):
f_char = ''
while node != :
f_char = + f_char
node =
# print f_char
return f_char
def display(self):
y_node()
def find_node(self, string):
res_node =
for i in string:
res_node = res_en[i]
return res_node
def association(self, node):
# 调用此函数前应该先将恢复成空列表
if ( != None):
if > 0:
(node)
for char in 'abcdefghijklmnopqrstuvwxyz':
if char in en:
ation(en[char])
def output_association(self, char):
char = str(char).lower()
= []
result_list = []
ation(_node(char))
(cmp=CMP)
if len() > 0:
for i in :
result_(ck(i))
if self.__OpenCorrect__ == 0:
result_(1, t(char))
# print 'result_list',result_list
return result_list
def correct(self, string):
= []
p = _node(string[:-1])
ation(p)
(cmp=CMP)
if len() > 1:
return ck([0])
def train(trie, path):
# f = open(r'')
f = open(path)
word = ()
()
word = (' ')
for i in word:
(i)
trie = Trie()
trie.__OpenCorrect__ = 0
def save_model(T):
f1 = open("", 'wb')
(T, f1)
()
def load_model(path):
f2 = open(path, 'rb')
trie = (f2)
()
print '================= END ====================='
class UI(QDialog):
def __init__(self, parent=None):
super(UI, self).__init__(parent)
QSList = QStringList()
# default
# QSList<<'One'<<'Tow'<<'Three'<<'Four'<<'Five'
# instance of Completer class
cmp = Completer(QSList)
global edit
edit = TextEdit()
tPointSize(80)
pleter(cmp)
dowTitle(u"智能文本编辑器")
button1 = QPushButton(u"训练模型")
button2 = QPushButton(u"保存文本文件")
button3 = QPushButton(u"打开文本文件")
'''
buttons = QushButton()
'''
'''
定义按钮,()内为按钮名称
'''
t(button1, SIGNAL("clicked()"), _file)
t(button2, SIGNAL("clicked()"), 2)
t(button3, SIGNAL("clicked()"), 3)
'''
关联按钮与函数格式同上,触发为clicked()单击,最后一个参数为
类内函数
'''
layout = QGridLayout()
get(edit, 0, 1, 1, 5)
get(button1, 2, 1)
get(button2, 2, 3)
get(button3, 2, 5)
'''
按钮布局
'''
out(layout)
()
def center(self):
screen = QDesktopWidget().screenGeometry()
size = ry()
((() - ()) / 2, (() - ()) / 2)
def get_file(self):
s = nFileName(self, "Open file dialog", "/", "TXT Files(*.txt)")
train(trie, s)
def func2(self):
s = eFileName(self, "文件保存", "C:/", "All Files (*);Text Files (*.txt)")
f = open(s, 'w')
(nText())
()
def func3(self):
s = nFileName(self, "Open file dialog", "/", "TXT Files(*.txt)")
f = open(s)
t(g(()))
()
class TextEdit(QTextEdit):
def __init__(self, parent=None):
super(TextEdit, self).__init__(parent)
= None
self.p = ''
= 0
def setCompleter(self, completer):
if :
nect(, 0, 0)
= completer
if (not ):
return
get(self)
pletionMode(ompletion)
eSensitivity(sensitive)
t(, SIGNAL('activated(QString)'), Completion)
def completer(self):
return
def insertCompletion(self, string):
# get cursor position
tc = rsor()
# selectd ranges
sition(fWord, chor)
# replace selected ranges
Text(string)
self.p += str(string)
# set cursor pos back to original pos
tCursor(tc)
def textUnderCursor(self):
tc = rsor()
(derCursor)
return edText()
def keyPressEvent(self, e):
'''
if () != _Backspace:
self.p = self.p + ()
+=1
print 'yes'
else:
self.p = self.p[:-1]
-=1
'''
print 'p ', self.p
print 'pressed >> ', ()
if ( and ().isVisible()):
if () in (_Enter, _Return, _Escape, _Tab, _Backtab):
()
return
isShortcut = ((ers() & lModifier) and () == _E)
if (not or not isShortcut):
super(TextEdit, self).keyPressEvent(e)
ctrlOrShift = ers() & (lModifier | odifier)
if (not or (ctrlOrShift and ().isEmpty())):
return
eow = QString("~!@#$%^&*()_+{}|:"<>?,./;'[]-=")
hasModifier = (ers() != fier) and not ctrlOrShift
completionPrefix = derCursor()
# hide popup while matching invalid cases if (not isShortcut and (hasModifier or ().isEmpty() or () < 1 or ns(().right(1)))): ().hide() return (completionPrefix) ().setCurrentIndex(tionModel().index(0, 0)) cr = Rect() th(().sizeHintForColumn(0) + ().verticalScrollBar().sizeHint().width()) word = (' ')[:-1] self.p = '' for k in xrange(len(word)): self.p += word[k] print 'self.p=', self.p te(cr)class Completer(QCompleter): def __init__(self, stringlist, parent=None): super(Completer, self).__init__(parent) list = stringlist el(QStringListModel()) # update function will trigger while the text has been modified def update(self, completionText): # generate a new QStringList instance qsList = QStringList() # generate hint lists which returns by customatic definitions newList = genMyStrList(completionText) for item in newList: (item) list = qsList # filteredList = (completionText, sensitive) ().setStringList(list) ().setCurrentIndex(().index(0, 0))# the function below defined a way to generate a string listdef genMyStrList(key): my_str_list = _association(key) return my_str_listdef main(): app = QApplication() sEvents() form = UI() () # (form) _() window = QMainWindow() Bar().showMessage('Yuan Ziqi') menubar = r dowTitle('Auto Complete Demo') (400, 200) (400, 100) edit = TextEdit() tPointSize(40) pleter(cmp) # bt = addbutton() # kWidget(bt) tralWidget(edit) () (_())if __name__ == '__main__': print 'app is running successfully' main()
2023年12月6日发(作者:居宝)
基于trie树的具有联想功能的文本编辑器
之前的软件设计与开发实践课程中,自己构思的大作业题目。做的具有核心功能,但是还欠缺边边角角的小功能和持久化数据结构,先放出
来,有机会一点点改。github:
数据结构,使用过程截图以及源代码如下:
#数据结构
**trie树**
trie树相应的介绍点击链接
trie树在python文件中的类型定义
Node定义
#GUI设计界面
首先,用较大的文本文件进行训练,完成trie的树的训练。本文件夹下提供了一个文件作为示例。
在之后的输入会弹出提示框
#!/usr/bin/python
# -*- coding: utf-8 -*-
import PyQt4
from import *
from import *
import
import sys
import pickle
print '===================start======================='
class Node:
def __init__(self):
= None
en = {} # children is of type {char, Node}
= 0
= None
def CMP(a, b):
return -
class Trie:
def __init__(self):
= Node()
= []
self.__OpenCorrect__ = 0
def insert(self, key): # key is of type string
# key should be a low-case string, this must be checked here!
node =
for char in key:
if char not in en:
child = Node()
en[char] = child
= char
= node
node = child
else:
node = en[char]
# = key
+= 1
def search(self, key):
node =
for char in key:
if char not in en:
return None
else:
node = en[char]
return
def display_node(self, node):
if ( != None):
for char in 'abcdefghijklmnopqrstuvwxyz':
if char in en:
y_node(en[char])
return
def fallback(self, node):
f_char = ''
while node != :
f_char = + f_char
node =
# print f_char
return f_char
def display(self):
y_node()
def find_node(self, string):
res_node =
for i in string:
res_node = res_en[i]
return res_node
def association(self, node):
# 调用此函数前应该先将恢复成空列表
if ( != None):
if > 0:
(node)
for char in 'abcdefghijklmnopqrstuvwxyz':
if char in en:
ation(en[char])
def output_association(self, char):
char = str(char).lower()
= []
result_list = []
ation(_node(char))
(cmp=CMP)
if len() > 0:
for i in :
result_(ck(i))
if self.__OpenCorrect__ == 0:
result_(1, t(char))
# print 'result_list',result_list
return result_list
def correct(self, string):
= []
p = _node(string[:-1])
ation(p)
(cmp=CMP)
if len() > 1:
return ck([0])
def train(trie, path):
# f = open(r'')
f = open(path)
word = ()
()
word = (' ')
for i in word:
(i)
trie = Trie()
trie.__OpenCorrect__ = 0
def save_model(T):
f1 = open("", 'wb')
(T, f1)
()
def load_model(path):
f2 = open(path, 'rb')
trie = (f2)
()
print '================= END ====================='
class UI(QDialog):
def __init__(self, parent=None):
super(UI, self).__init__(parent)
QSList = QStringList()
# default
# QSList<<'One'<<'Tow'<<'Three'<<'Four'<<'Five'
# instance of Completer class
cmp = Completer(QSList)
global edit
edit = TextEdit()
tPointSize(80)
pleter(cmp)
dowTitle(u"智能文本编辑器")
button1 = QPushButton(u"训练模型")
button2 = QPushButton(u"保存文本文件")
button3 = QPushButton(u"打开文本文件")
'''
buttons = QushButton()
'''
'''
定义按钮,()内为按钮名称
'''
t(button1, SIGNAL("clicked()"), _file)
t(button2, SIGNAL("clicked()"), 2)
t(button3, SIGNAL("clicked()"), 3)
'''
关联按钮与函数格式同上,触发为clicked()单击,最后一个参数为
类内函数
'''
layout = QGridLayout()
get(edit, 0, 1, 1, 5)
get(button1, 2, 1)
get(button2, 2, 3)
get(button3, 2, 5)
'''
按钮布局
'''
out(layout)
()
def center(self):
screen = QDesktopWidget().screenGeometry()
size = ry()
((() - ()) / 2, (() - ()) / 2)
def get_file(self):
s = nFileName(self, "Open file dialog", "/", "TXT Files(*.txt)")
train(trie, s)
def func2(self):
s = eFileName(self, "文件保存", "C:/", "All Files (*);Text Files (*.txt)")
f = open(s, 'w')
(nText())
()
def func3(self):
s = nFileName(self, "Open file dialog", "/", "TXT Files(*.txt)")
f = open(s)
t(g(()))
()
class TextEdit(QTextEdit):
def __init__(self, parent=None):
super(TextEdit, self).__init__(parent)
= None
self.p = ''
= 0
def setCompleter(self, completer):
if :
nect(, 0, 0)
= completer
if (not ):
return
get(self)
pletionMode(ompletion)
eSensitivity(sensitive)
t(, SIGNAL('activated(QString)'), Completion)
def completer(self):
return
def insertCompletion(self, string):
# get cursor position
tc = rsor()
# selectd ranges
sition(fWord, chor)
# replace selected ranges
Text(string)
self.p += str(string)
# set cursor pos back to original pos
tCursor(tc)
def textUnderCursor(self):
tc = rsor()
(derCursor)
return edText()
def keyPressEvent(self, e):
'''
if () != _Backspace:
self.p = self.p + ()
+=1
print 'yes'
else:
self.p = self.p[:-1]
-=1
'''
print 'p ', self.p
print 'pressed >> ', ()
if ( and ().isVisible()):
if () in (_Enter, _Return, _Escape, _Tab, _Backtab):
()
return
isShortcut = ((ers() & lModifier) and () == _E)
if (not or not isShortcut):
super(TextEdit, self).keyPressEvent(e)
ctrlOrShift = ers() & (lModifier | odifier)
if (not or (ctrlOrShift and ().isEmpty())):
return
eow = QString("~!@#$%^&*()_+{}|:"<>?,./;'[]-=")
hasModifier = (ers() != fier) and not ctrlOrShift
completionPrefix = derCursor()
# hide popup while matching invalid cases if (not isShortcut and (hasModifier or ().isEmpty() or () < 1 or ns(().right(1)))): ().hide() return (completionPrefix) ().setCurrentIndex(tionModel().index(0, 0)) cr = Rect() th(().sizeHintForColumn(0) + ().verticalScrollBar().sizeHint().width()) word = (' ')[:-1] self.p = '' for k in xrange(len(word)): self.p += word[k] print 'self.p=', self.p te(cr)class Completer(QCompleter): def __init__(self, stringlist, parent=None): super(Completer, self).__init__(parent) list = stringlist el(QStringListModel()) # update function will trigger while the text has been modified def update(self, completionText): # generate a new QStringList instance qsList = QStringList() # generate hint lists which returns by customatic definitions newList = genMyStrList(completionText) for item in newList: (item) list = qsList # filteredList = (completionText, sensitive) ().setStringList(list) ().setCurrentIndex(().index(0, 0))# the function below defined a way to generate a string listdef genMyStrList(key): my_str_list = _association(key) return my_str_listdef main(): app = QApplication() sEvents() form = UI() () # (form) _() window = QMainWindow() Bar().showMessage('Yuan Ziqi') menubar = r dowTitle('Auto Complete Demo') (400, 200) (400, 100) edit = TextEdit() tPointSize(40) pleter(cmp) # bt = addbutton() # kWidget(bt) tralWidget(edit) () (_())if __name__ == '__main__': print 'app is running successfully' main()