なんかいろいろこんぴゅーたかんけいのなぐりがき

なんか勉強しているこんぴゅーた関係のことのメモやそれ以外のことを書こうかなあ...

logs

スポンサーサイト

上記の広告は1ヶ月以上更新のないブログに表示されています。
新しい記事を書く事で広告が消せます。

goo辞書を使って... 改良版の続き

さらに改良してみた

タブで履歴の補完
F2で補完される単語のリスト表示
動作状態の表示
その他いろいろGUIの変更

sample.jpg

ソースコードのコメントに使っている英語は文法がでたらめだし、単語も間違って使っている場合が多々あるが、まあ、なんとか意味を推測して汲めるはず・・・


#coding:utf-8
#main.py
from Tkinter import *
from tkMessageBox import *
from ScrolledText import *
import urllib2,sys,os,glob
import tabcom

#goo dictionary's URL
urlb = "http://dictionary.goo.ne.jp/srch/all/"
urla = "/m0u/"
word = ""#input word
mean_flag = False#is a word's mean exist?
input_flag = False#something words inputed?
DIR = "dict"#searched means saved this directory

def keyEvent(evt):
global input_flag
if evt.keysym == "F2":
showList()
else: input_flag = True
def showList():
global tc,word,input_flag
setMessage("候補取得中")
if input_flag :
word = buf.get()
input_flag = False

comp_list,count = tc.getCandidate(word,list=True)

if comp_list == None:
setMessage("候補が見つかりませんでした",bg="RED")
return
else:
print "list = ",comp_list
print "count =",count
st.delete("1.0","end")
st.tag_config("tag1",background="GREEN",foreground="WHITE")
i = 0
for element in comp_list:
if i == count:
st.insert("end",element.decode("utf-8")+"\n","tag1")
else:
st.insert("end",element.decode("utf-8")+"\n")
i+=1
setMessage("候補取得完了")
def tabHis(arg=None):
"""
TabComplite word witch you searched already
"""
setMessage("候補取得中")

global tc,word,input_flag

#if inputed,get inputed word
if input_flag :
word = buf.get()
input_flag = False
print "tabHis:word=",word
#get candidated word
ret = tc.getCandidate(word)

if ret != "":
buf.set(ret)
st.delete("1.0","end")
# read saved mean
r = open(os.path.join(DIR,"")+ret+".mydic","r")
for line in r:
st.insert("end",line.decode("utf-8"))
r.close()
setMessage("候補取得完了")
else:
setMessage("候補が見つかりませんでした",bg="RED")

def clean(word):
"""
clear .mydict file,if it's size is 0
"""
target = os.path.join(os.getcwd(),DIR,word+".mydic")

if os.path.getsize(target) == 0:
os.remove(target)
return True
else:
return False

def quit():
"""
quit this program
"""
sys.exit()
def clear(arg=None):
"""
clear Entry
"""
st.delete("1.0","end")
def setMessage(msg,bg="GREEN",fg="BLACK"):
global label_text
label_text.set(msg)
label.configure(bg=bg,fg=fg)
label.update()
def search(arg=None):
"""
search word from goo dictionary in the Internet
"""
global mean_flag,word
setMessage("Webから意味を取得中")
word = buf.get()

# .
setMessage(label_text.get()+".")

w = open(os.path.join(DIR,word+".mydic"),"w")

#get html date from Web
info = urllib2.urlopen(urlb+word+urla)

# ..
setMessage(label_text.get()+".")

#extract means from info
for line in info:
if line.find('"meanings"') != -1:
mean_flag = True
continue
if mean_flag:
mean_flag = False
try:
line = line.replace("</li>","")
st.insert("end",line.decode("utf-8"))
w.write(line)
except:pass

w.close()

# ...
setMessage(label_text.get()+".")

#if cleaned -> return True,not cleand -> reutrn False
if clean(word):
setMessage("見つかりませんでした",bg="RED")
else:
setMessage("取得完了")
st.insert("end","\n")



#make tabcom instance
tc = tabcom.TabCom(DIR)

# if DIR directory is not exists,make the directory
if not os.path.exists(DIR):
os.mkdir(DIR)

#set wigets
root = Tk()
root.option_add("*font",("FixedSys",12))
root.title("英和辞書GOO")
buf = StringVar()
label_text = StringVar()
label_text.set("waiting")
label = Label(root,textvariable=label_text,bg="GREEN",width=50,relief=RIDGE)
label.grid(row=0,column=0)
entry = Entry(width=50,textvariable=buf)
entry.grid(row=1,column=0,sticky=W)
entry.bind("<Return>",search)
entry.bind("<Escape>",clear)
entry.bind("<Tab>",tabHis)
entry.bind("<Key>",keyEvent)
entry.focus_set()
button = Button(text="search",takefocus=0,width = 30,command=search)
button.grid(row=1,column=0,sticky=E)
button3 = Button(text="clear",takefocus=0,width = 10,command=clear)
button3.grid(row=2,column=0)
st = ScrolledText(width=100,takefocus=0,height=20)
st.grid(row=3,column=0)
button2 = Button(text="quit",width = 30,takefocus=0,command=quit)
button2.grid(row=4,column=0)
root.mainloop()
#Text tag
st.tag_config("tag1",bg="GREEN",fg="WHITE")


#tabcom.py
import glob,os
def main():
o = TabCom(dict="dict")
o.getCandidate("a")
class TabCom():
def __init__(self,dict):
self.dictPath = os.path.join(os.getcwd(),dict)
self.word = None
self.count = 0
self.list = []
self.candidate = []
def getCandidate(self,word,list=False):
"""
select match word in candidate
"""

if word != self.word :
print "new word!!"
self.word = word
self.resetCandidate()
self.setCount(0)
x = 0
last_word = self.candidate[-1]
loop_end = False
while True:
cmp_word = self.candidate[x]
#set loop end
if cmp_word == last_word: loop_end = True
else:pass

#short length word from inputed word
if len(self.word) > len(cmp_word):
print("remove(short)")
self.candidate.remove(self.candidate[x])
self.list.remove(self.list[x])
#remove candidate NoMatch word and
elif cmp_word.find(self.word) != 0:
print("remove(NotMatch)")
self.candidate.remove(self.candidate[x])
self.list.remove(self.list[x])
else: x += 1

#if end , break
if loop_end : break
else:pass

else:
print "same word"
#if this method used for getList,don't addCount
if not list :self.addCount(1)

#print result
print "count = ",self.count
#print "result = ",self.candidate[self.count]
print "candidate = ",self.candidate
print "list = ",self.list

if not list:
if len(self.candidate) <= 0: return ""
else: return self.candidate[self.count]
else :
if len(self.candidate) <= 0: return None,None
else: return self.candidate,self.count


def getCount(self):
return self.count
def addCount(self,num):
self.count += num
if self.count >= len(self.candidate):
self.setCount(0)
def setCount(self,num):
if num > len(self.candidate):
num = 0
self.count = num
def resetCandidate(self):
"""
get TabComplete Candidates
"""

self.candidate = []
self.list = os.listdir(self.dictPath)
for element in self.list:
pos = element.find(".mydic")
# remove not .mydic element
if pos == -1:
self.list.remove(element)
continue
else:
self.candidate.append(element[:pos])

if __name__ == "__main__":
main()

スポンサーサイト

トラックバックURL

http://ilovevim.blog42.fc2.com/tb.php/110-86ca0366

この記事へのトラックバック

この記事へのコメント

コメント投稿フォーム

Paging Navigation

Navigations, etc.

上記広告は1ヶ月以上更新のないブログに表示されています。新しい記事を書くことで広告を消せます。