2012년 2월 24일 금요일

리눅스 사전

설치방법
apt-get install python-setuptools
easy_install pip
pip install beautifulsoup
apt-get install python-gtk2 ; apt-get install python-glade2

아래에 있는 Dict.py 내용으로 Dict.py 파일을 만든다.
같은 폴더에 Main.glade 내용으로 Main.glade 파일을 만든다.


  • 기능
    • 기본적인 단어검색
    • 다음 dic 을 이용해서 만들어서 인터넷 연결시 사용해야 함
    • 검색결과 우분투 notification 에서 나옴
    • 어플을 뛰어 놓은 상태에서 텍스트 복사시에 자동으로 검색함.
  • 필요한 lib
    • glade
    • pygtk
    • BeautifulSoup

Dict.py
#-*- coding: utf-8 -*-
# coding: utf-8
# author : spyrogira256@gmail.com

import pygtk
pygtk.require("2.0")



import gtk, gobject
import gtk.glade
import sys

import pynotify

import httplib
#import urllib2
from BeautifulSoup import BeautifulSoup

# even in Python this is globally nasty <img src="http://developer.ubuntu.com/wp-includes/images/smilies/icon_smile.gif" alt=":)" class="wp-smiley"> , do something nicer in your own code
capabilities = {'actions':             False,
        'body':                False,
        'body-hyperlinks':     False,
        'body-images':         False,
        'body-markup':         False,
        'icon-multi':          False,
        'icon-static':         False,
        'sound':               False,
        'image/svg+xml':       False,
        'private-synchronous': False,
        'append':              False,
        'private-icon-only':   False}


ENTER_KEY = 65293
DAUM_DIC = "small.dic.daum.net"
DAUM_QUERY = "/search.do?q="

MEANS= [{'title':"영어사전",'search_class': "txt_means_KUEK"},
        {'title':"영영사전",'search_class': "txt_means_WOEE"},
        {'title': "국어사전", 'search_class' : "txt_means_KOKK"},
        {'title':"일어사전", 'search_class' : "txt_means_KUKJ"},
        {'title' : "중국어사전", 'search_class' : "txt_means_KOKC"}] 
# ENG_MEAN = "txt_means_KUEK"  # 영어사전 
# EE_MEAN = "txt_means_WOEE" # 영영사전 
# KOR_MEAN = "txt_means_KOKK" # 국어사전 
# JP_MEAN = "txt_means_KUKJ" # 일어 
# CH_MEAN = "txt_means_KOKC" # 중국어 


class ClipboardInfo:
    pass

class DictHTMLParse :
    
    def parse(self, html_doc):
        soup = BeautifulSoup(html_doc)
        result = ""
        for mean in MEANS :
            fetchData= soup.fetch('div',{'class' : mean['search_class']})
            if len(fetchData) > 0 :
                result += mean['title'] + "\r\n"
                result += fetchData[0].contents[0] + "\r\n\r\n"
        
        return result

class Dict:

    # signal handler called when the clipboard returns text data
    def clipboard_text_received(self, clipboard, text, data):
        if not text or text == '':
            return

        if self.cbi.text !=text and len(text) > 0 :
            print "cbi text %s " % text
            self.txt_entry.set_text(text)
            self.cbi.text = text
            self.daum_search(text)

        return

     # get the clipboard text
    def fetch_clipboard_info(self):
        self.clipboard.request_text(self.clipboard_text_received)
        return True


    def __init__(self):
        file = "Main.glade"
        self.builder = gtk.Builder()
        self.builder.add_from_file(file)
        self.builder.connect_signals(self)
        self.window = self.builder.get_object("MainWindow")
        self.txt_entry = self.builder.get_object("txt_entry")
        self.txtview = self.builder.get_object("txtview")
        self.cbi = ClipboardInfo()
        self.cbi.text= ""

        dic = {"search_callback" : self.search_callback, 
               "on_exit_click": self.on_exit_click ,
               "txt_key_press": self.txt_key_press
               }
        self.builder.connect_signals(di설치방법
apt-get install pip
apt-get install glade
pip install beautifulsoup

아래에 있는 Dict.py 내용으로 Dict.py 파일을 만든다.
같은 폴더에 Main.glade 내용으로 Main.glade 파일을 만든다. c)

        # 클립보드 초기화 
        self.clipboard = gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD)
        self.clipboard.set_text("",-1)
        self.clipboard.clear()

        # 백그라운드 쓰레드 1.5 초 간격으로 클립보드 확인 
        gobject.timeout_add(1500, self.fetch_clipboard_info)

        self.window.show()
        
    def on_exit_click(self,widget,data=None):
        gtk.main_quit()
    
    def search_callback(self,widget, data=None):
        self.daum_search(self.txt_entry.get_text())

    def txt_key_press(self,widget, event):
        if event.keyval == ENTER_KEY :
            self.daum_search(self.txt_entry.get_text())
            print self.txt_entry.get_text()

               
    def daum_search(self, search_text=None):
        conn = httplib.HTTPConnection(DAUM_DIC)
        conn.request("GET",DAUM_QUERY+search_text)
        res = conn.getresponse()
        parser = DictHTMLParse()

        textBuffer = gtk.TextBuffer()
        text = parser.parse(res.read())
        textBuffer.set_text(text)

        self.txtview.set_buffer(textBuffer)
        notify = Notify()
        notify.show(text)
        
class Notify :
    def initCaps(self):
        caps = pynotify.get_server_caps()
        if caps is None:
            print "Failed to receive server caps."
            sys.exit(1)
        
        for cap in caps:
            capabilities[cap] = True
 
    def printCaps(self):
        info = pynotify.get_server_info()
        print "Name:          " + info["name"]
        print "Vendor:        " + info["vendor"]
        print "Version:       " + info["version"]
        print "Spec. Version: " + info["spec-version"]
 
        caps = pynotify.get_server_caps()
        if caps is None:
            print "Failed to receive server caps."
            sys.exit (1)
 
            print "Supported capabilities/hints:"
        if capabilities['actions']:
            print "\tactions"
        if capabilities['body']:
            print "\tbody"
        if capabilities['body-hyperlinks']:
            print "\tbody-hyperlinks"
        if capabilities['body-images']:
            print "\tbody-images"
        if capabilities['body-markup']:
            print "\tbody-markup"
        if capabilities['icon-multi']:
            print "\ticon-multi"
        if capabilities['icon-static']:
            print "\ticon-static"
        if capabilities['sound']:
            print "\tsound"
        if capabilities['image/svg+xml']:
            print "\timage/svg+xml"
        if capabilities['private-synchronous']:
            print "\tprivate-synchronous"
        if capabilities['append']:
            print "\tappend"
        if capabilities['private-icon-only']:
            print "\tprivate-icon-only"
 
        print "Notes:"
        if info["name"] == "notify-osd":
            print "\tx- and y-coordinates hints are ignored"
            print "\texpire-timeout is ignored"
            print "\tbody-markup is accepted but filtered"
        else:
            print "\tnone"
 
    def __init__(self):
           
        if not pynotify.init("icon-summary-body"):
            sys.exit(1)
 
       # call this so we can savely use capabilities dictionary later

        self.initCaps()
 
       # show what's supported
        self.printCaps()
 
        # try the icon-summary-body case
        
    def show(self,text) :
        n = pynotify.Notification (text)
        n.show()


if __name__ == "__main__" :
    dict = Dict()
    gtk.main()


Main.glade


<?xml version="1.0" encoding="UTF-8"?>
<interface>
  <!-- interface-requires gtk+ 3.0 -->
  <object class="GtkWindow" id="MainWindow">
    <property name="can_focus">False</property>
    <property name="has_resize_grip">False</property>
    <signal name="delete-event" handler="on_exit_click" swapped="no"/>
    <child>
      <object class="GtkVBox" id="vbox1">
        <property name="visible">True</property>
        <property name="can_focus">False</property>
        <child>
          <object class="GtkHBox" id="hbox1">
            <property name="visible">True</property>
            <property name="can_focus">False</property>
            <child>
              <object class="GtkEntry" id="txt_entry">
                <property name="visible">True</property>
                <property name="can_focus">True</property>
                <property name="invisible_char">•</property>
                <property name="shadow_type">none</property>
                <signal name="key-press-event" handler="txt_key_press" swapped="no"/>
              </object>
              <packing>
                <property name="expand">True</property>
                <property name="fill">True</property>
                <property name="position">0</property>
              </packing>
            </child>
            <child>
              <object class="GtkButton" id="b_search">
                <property name="label" translatable="yes">찾기</property>
                <property name="visible">True</property>
                <property name="can_focus">True</property>
                <property name="receives_default">True</property>
                <property name="use_action_appearance">False</property>
                <signal name="clicked" handler="search_callback" object="txt_entry" swapped="no"/>
              </object>
              <packing>
                <property name="expand">True</property>
                <property name="fill">True</property>
                <property name="position">1</property>
              </packing>
            </child>
            <child>
              <object class="GtkButton" id="b_close">
                <property name="label" translatable="yes">닫기</property>
                <property name="visible">True</property>
                <property name="can_focus">True</property>
                <property name="receives_default">True</property>
                <property name="use_action_appearance">False</property>
                <signal name="clicked" handler="on_exit_click" swapped="no"/>
              </object>
              <packing>
                <property name="expand">True</property>
                <property name="fill">True</property>
                <property name="position">2</property>
              </packing>
            </child>
          </object>
          <packing>
            <property name="expand">False</property>
            <property name="fill">True</property>
            <property name="position">0</property>
          </packing>
        </child>
        <child>
          <object class="GtkScrolledWindow" id="scrolledwindow1">
            <property name="visible">True</property>
            <property name="can_focus">True</property>
            <property name="shadow_type">in</property>
            <child>
              <object class="GtkTextView" id="txtview">
                <property name="width_request">300</property>
                <property name="height_request">300</property>
                <property name="visible">True</property>
                <property name="can_focus">True</property>
                <property name="vscroll_policy">natural</property>
              </object>
            </child>
          </object>
          <packing>
            <property name="expand">True</property>
            <property name="fill">True</property>
            <property name="position">1</property>
          </packing>
        </child>
      </object>
    </child>
  </object>
</interface>



  1. tray로 넣기
  2. 강세 추가
  3. 발음듣기 추가
  4. screenlet로 추가하기

댓글 없음:

댓글 쓰기