#!/usr/bin/env python
# -*- coding: utf-8 -*-
#gnetdict script 檔範例
#License: GNU General Public License
#Author: 洪任諭 Hong Jen Yee (PCMan) <pcman.tw@gmail.com>
import sys, os
#顯示 script 相關資訊
def info():
print """
script_version=1.0
name=Yahoo! 奇摩線上字典
url=http://tw.dictionary.yahoo.com/
version=0.1
author=洪任諭 (PCMan) <pcman.tw@gmail.com>
"""
def get_webpage( url ):
import urllib, re
f = urllib.urlopen( url )
content = f.read()
f.close()
reg = re.compile( '<blockquote>((.*\n)*.*)</blockquote>', re.MULTILINE | re.IGNORECASE )
m = reg.search( content )
if m:
content = '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body>'
content += m.group(1)
content += '</body></html>'
else:
content = ''
return content
#查詢單字,查詢成功把結果網頁內容輸出在 stdout,
#註:stdout 輸出的第一行需為查詢網頁的 url
#並且 return True,否則 return False
def query(word):
url = 'http://tw.dictionary.yahoo.com/search?ei=UTF-8&p=' + urllib.quote_plus(word)
result = get_webpage( url )
if result == '': #查詢失敗
return False
#查詢成功,把結果輸出到 stdout
print url #stdout 輸出的第一行需為查詢網頁的 url
print result
return True
#開啟 url,開啟成功把結果網頁內容輸出在 stdout,
#註:stdout 輸出的第一行需為此網頁的 url
#並且 return True。禁止連接此 url 則 return False
def open_url(url):
#只支援顯示 'http://tw.dictionary.yahoo.com/search?' 下的網頁
if url.startswith('/search?'):
url = 'http://tw.dictionary.yahoo.com' + url
content = get_webpage(url)
if content != '':
print url #stdout 輸出的第一行需為查詢網頁的 url
print content
return True
return False
#快取圖檔,從 url 下載圖片,並快取到本機暫存檔
#快取成功,把本機暫存擋路徑輸出在 stdout,
#並且 return True。禁止顯示此圖片則 return False
def cache_image(url):
basename = os.path.basename(url)
#快取圖片的目錄
cache_dir=os.path.expanduser('~/.gnetdict/yahoo/')
if not os.path.exists(cache_dir): #若不存在則建立
os.mkdir(cache_dir)
cache_path = cache_dir + basename
if not os.path.exists( cache_path ):
import urllib
urllib.urlretrieve( url, cache_path )
print cache_path #把本機快取圖檔路徑輸出到stdout
return True
if __name__=='__main__':
#執行沒有任何參數,在stdout顯示程式資訊
if len(sys.argv) <= 1:
info();
elif len(sys.argv) >= 3:
#query 參數查詢單字,在 stdout 輸出要顯示的內容
#argv[2] 是要查的單字
#查詢成功 exit(0), 無法顯示則 exit(1)
if sys.argv[1] == 'query':
if query( sys.argv[2] ):
exit(0)
else:
exit(1)
#url 參數存取超連結,在 stdout 輸出要顯示的內容
#argv[2] 是要連接的 url
#存取成功 exit(0), 禁止連到這個 url 則 exit(1)
elif sys.argv[1] == 'open_url':
if open_url( sys.argv[2] ):
exit(0)
else:
exit(1)
#img 參數處理圖片,下載並快取網路上的圖檔
#argv[2] 是要連接的 image url
#快取成功 exit(0),並在 stdout 輸出"本機"的圖片檔路徑
#快取失敗,或禁止顯示此圖片,則 exit(1)
elif sys.argv[1] == 'img':
if cache_image( sys.argv[2] ):
exit(0)
else:
exit(1)
else: #不支援的參數,exit(2) 表示發生嚴重錯誤
exit(2)
else: #不支援的參數,exit(2) 表示發生嚴重錯誤
exit(2)