<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" 
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>Thinking more...-Python</title>
<link>http://blog.roodo.com/thinkingmore/archives/cat_706629.html</link>
<description>Just thinking more...&amp;nbsp;訂閱 RSS

var gaJsHost = ((&quot;https:&quot; == document.location.protocol) ? &quot;https://ssl.&quot; : &quot;http://www.&quot;);
document.write(unescape(&quot;%3Cscript src=&#039;&quot; + gaJsHost + &quot;google-analytics.com/ga.js&#039; type=&#039;text/javascript&#039;%3E%3C/script%3E&quot;));















  google.load(&quot;jquery&quot;, &quot;1.2&quot;);
  google.setOnLoadCallback( function() {
    try {
      var pageTracker = _gat._getTracker(&quot;UA-97150-7&quot;);
      pageTracker._trackPageview();
    }catch(err) {}
    $(&quot;pre &gt; br&quot;).each( function() { $(this).replaceWith( &quot;\n&quot; ); } );
    $(&quot;textarea &gt; br&quot;).each( function() { $(this).replaceWith( &quot;\n&quot; ); } );
    SyntaxHighlighter.config.ClipboardSwf = &#039;http://alexgorbatchev.com/pub/sh/2.0.296/scripts/clipboard.swf&#039;;
    SyntaxHighlighter.all();
    dp.SyntaxHighlighter.ClipboardSwf = &#039;http://alexgorbatchev.com/pub/sh/2.0.296/scripts/clipboard.swf&#039;;
    dp.SyntaxHighlighter.HighlightAll(&#039;code&#039;);
  } );

</description>
<language>zh-tw</language>
<generator>Roodo Blog System</generator>
<copyright>All Rights Reserved</copyright>
<atom:link href="http://blog.roodo.com/thinkingmore/archives/cat_706629.xml" rel="self" type="application/rss+xml" />
<item>
	<title>發佈你的 Python 程式</title>
	<description><![CDATA[
			因為覺得老是從專案目錄下執行程式也不是很方便，所以想，應該要把程式弄的標準一點，能依循比較正式的方法去發佈程式。一般來說，各大語言都會有建議怎麼去散佈、發佈你的程式。

所以今天早上胡亂地用 python deployment guide 找了一下，發現找不到這樣的 guide。後來才發現找錯關鍵字，python 裡是用 distribute/spreading，改變一下關鍵字，就能找到這幾份：Distributing Python ModulesLinux.com :: Spreading Python applications

文件不難，照著試一試，的確一下子就寫好了。

比較麻煩的是程式如果要用到 module 裡的一些檔案時，會不知道路徑。舉例來說，我是把 glade 產生的 gtkbuilder ui 檔案放在 module 路徑下，那程式該怎麼讀取呢??總不能寫死吧。還好 Stack Overflow有解答：Retrieving python module path，就是用 os.path.dirname(module.__file__) 取得。

		]]>
	</description>
	<content:encoded><![CDATA[
			因為覺得老是從專案目錄下執行程式也不是很方便，所以想，應該要把程式弄的標準一點，能依循比較正式的方法去發佈程式。一般來說，各大語言都會有建議怎麼去散佈、發佈你的程式。<br />
<br />
所以今天早上胡亂地用 python deployment guide 找了一下，發現找不到這樣的 guide。後來才發現找錯關鍵字，python 裡是用 distribute/spreading，改變一下關鍵字，就能找到這幾份：<ul><li><a href="http://www.python.org/doc/2.6.4/distutils/index.html">Distributing Python Modules</a></li><li><a href="http://www.linux.com/archive/feature/118439">Linux.com :: Spreading Python applications</a></li></ul><br />
<br />
文件不難，照著試一試，的確一下子就寫好了。<br />
<br />
比較麻煩的是程式如果要用到 module 裡的一些檔案時，會不知道路徑。舉例來說，我是把 glade 產生的 gtkbuilder ui 檔案放在 module 路徑下，那程式該怎麼讀取呢??總不能寫死吧。還好 <a href="http://stackoverflow.com/">Stack Overflow</a>有解答：<a href="http://stackoverflow.com/questions/247770/retrieving-python-module-path">Retrieving python module path</a>，就是用 os.path.dirname(module.__file__) 取得。<br />

		
		]]>
	</content:encoded>
	<link>http://blog.roodo.com/thinkingmore/archives/10766695.html</link>
	<guid>http://blog.roodo.com/thinkingmore/archives/10766695.html</guid>
	<category>Python</category>
	<pubDate>Thu, 19 Nov 2009 15:48:18 +0800</pubDate>
</item>
<item>
	<title>Bing translate in Python</title>
	<description><![CDATA[
			根據 Microsoft Translator HTTP 介面，然後用Python寫的。程式不長，其實跟 google translate 的方法很相似，最下面有使用範例。

附帶一提的，Bing翻譯網站上完全沒提到要怎麼申請 appid，申請 appid 要去 Bing Developer Center 申請，所以你要自己去申請，取得 appid 之後，把程式裡的 your_app_id 換成你申請的 appid。

#!/usr/bin/env python
# -*= coding: utf-8 -*-
import sys
import os
from urllib import urlencode
import urllib2
from urllib2 import Request, urlopen, URLError, HTTPError
import json
from translate import *

class BingTranslate:
	appid = 'your_app_id'
	base_uri = "http://api.microsofttranslator.com/V1/Http.svc"

	def __read_from_req( self, req ):
		try:
			response = urllib2.urlopen( req )
			result = response.read()
		except HTTPError, e:
			print e.code
			print e.read()
			result=""
		return result

	def detect( self, text ):
		uri="%s/Detect?appId=%s" % ( self.base_uri, self.appid )
		req = urllib2.Request( uri, text, { 'Content-Type':'text/plain'} )
		return self.__read_from_req( req )
	
	def getLanguageNames( self, locale=None ):
		"""
		Thanks MSDN, I still don't know the value of parameter 'locale'
		Don't pass any parameter to getLanguageNames, or you will get error.
		"""
		uri="%s/GetLanguageNames?appId=%s" % ( self.base_uri, self.appid )
		req = urllib2.Request( uri, locale, { 'Content-Type':'text/plain'} )
		return self.__read_from_req( req ).split( '\n' )

	def getLanguages( self ):
		uri="%s/GetLanguages?appId=%s" % ( self.base_uri, self.appid )
		req = urllib2.Request( uri, None, { 'Content-Type':'text/plain'} )
		return self.__read_from_req( req ).split("\r\n")

	def translate( self, text, fr="en", to="zh-CHT" ):
		uri="%s/Translate?appId=%s&from=%s&to=%s" % ( self.base_uri,
				self.appid, fr, to )
		req = urllib2.Request( uri, text, { 'Content-Type':'text/plain'} )
		return self.__read_from_req( req )

if __name__ == "__main__":
	t = BingTranslate()
	print t.translate( "test" )
	print t.translate( "鬼", "zh-CHT", "en" )
	print t.detect( "中文測試" )
	print t.detect( "中文测试" )
	names = t.getLanguageNames()
	langs = t.getLanguages()
	print "Language Names (total %d):" % len(names)
	for l in names:
		print l
	print "Languages (total %d):" % len(langs)
	for l in langs:
		print l


		]]>
	</description>
	<content:encoded><![CDATA[
			根據 <a href="http://msdn.microsoft.com/en-us/library/dd576285.aspx">Microsoft Translator HTTP 介面</a>，然後用<a href="http://www.python.org">Python</a>寫的。程式不長，其實跟 google translate 的方法很相似，最下面有使用範例。<br/>
<br/>
附帶一提的，<a href="http://www.microsofttranslator.com">Bing翻譯</a>網站上完全沒提到要怎麼申請 appid，申請 appid 要去 <a href="http://www.bing.com/developers/">Bing Developer Center</a> 申請，所以你要自己去申請，取得 appid 之後，把程式裡的 your_app_id 換成你申請的 appid。<br/>
<br/>
<pre name="code" class="python">#!/usr/bin/env python
# -*= coding: utf-8 -*-
import sys
import os
from urllib import urlencode
import urllib2
from urllib2 import Request, urlopen, URLError, HTTPError
import json
from translate import *

class BingTranslate:
	appid = 'your_app_id'
	base_uri = "http://api.microsofttranslator.com/V1/Http.svc"

	def __read_from_req( self, req ):
		try:
			response = urllib2.urlopen( req )
			result = response.read()
		except HTTPError, e:
			print e.code
			print e.read()
			result=""
		return result

	def detect( self, text ):
		uri="%s/Detect?appId=%s" % ( self.base_uri, self.appid )
		req = urllib2.Request( uri, text, { 'Content-Type':'text/plain'} )
		return self.__read_from_req( req )
	
	def getLanguageNames( self, locale=None ):
		"""
		Thanks MSDN, I still don't know the value of parameter 'locale'
		Don't pass any parameter to getLanguageNames, or you will get error.
		"""
		uri="%s/GetLanguageNames?appId=%s" % ( self.base_uri, self.appid )
		req = urllib2.Request( uri, locale, { 'Content-Type':'text/plain'} )
		return self.__read_from_req( req ).split( '\n' )

	def getLanguages( self ):
		uri="%s/GetLanguages?appId=%s" % ( self.base_uri, self.appid )
		req = urllib2.Request( uri, None, { 'Content-Type':'text/plain'} )
		return self.__read_from_req( req ).split("\r\n")

	def translate( self, text, fr="en", to="zh-CHT" ):
		uri="%s/Translate?appId=%s&from=%s&to=%s" % ( self.base_uri,
				self.appid, fr, to )
		req = urllib2.Request( uri, text, { 'Content-Type':'text/plain'} )
		return self.__read_from_req( req )

if __name__ == "__main__":
	t = BingTranslate()
	print t.translate( "test" )
	print t.translate( "鬼", "zh-CHT", "en" )
	print t.detect( "中文測試" )
	print t.detect( "中文测试" )
	names = t.getLanguageNames()
	langs = t.getLanguages()
	print "Language Names (total %d):" % len(names)
	for l in names:
		print l
	print "Languages (total %d):" % len(langs)
	for l in langs:
		print l
</pre>

		
		]]>
	</content:encoded>
	<link>http://blog.roodo.com/thinkingmore/archives/10669585.html</link>
	<guid>http://blog.roodo.com/thinkingmore/archives/10669585.html</guid>
	<category>Python</category>
	<pubDate>Thu, 12 Nov 2009 15:26:48 +0800</pubDate>
</item>
<item>
	<title>Python 練習 - Google translate</title>
	<description><![CDATA[
			因為看了A Bit? No!!!的這篇：写了个小小的翻译工具而做的小小練習。
基本上是作中翻英，但只要稍稍更動 langpair，就可以調整翻譯語言。


#!/usr/bin/env python
# -*= coding: utf-8 -*-
# http://www.oreillynet.com/pub/h/476 Encode Text for URLs
# http://evanjones.ca/python-utf8.html How to Use UTF-8 with Python
# http://abitno.linpie.com/a-small-translate-tool.html 寫了一個小小的翻譯工具
import sys
import os
from urllib import urlencode
import urllib2
import json

def get_json( uri ):
	response = urllib2.urlopen( uri )
	return response

def translate( text ):
	uri="http://www.ajax.googleapis.com/ajax/services/language/translate"
	query=urlencode( { 'v': '1.0', 'langpair': 'zh|en', 'q':
			text.encode('utf-8') } )
	uri = uri+"?"+query
	return json.load( get_json( uri ) )

text = unicode( sys.argv[1], "utf-8" )
print unicode( text ) + u" => " + translate( text )['responseData']['translatedText']


		]]>
	</description>
	<content:encoded><![CDATA[
			因為看了A Bit? No!!!的這篇：<a href="http://abitno.linpie.com/a-small-translate-tool.html">写了个小小的翻译工具</a>而做的小小練習。
基本上是作中翻英，但只要稍稍更動 langpair，就可以調整翻譯語言。

<pre name="code" class="python">
#!/usr/bin/env python
# -*= coding: utf-8 -*-
# http://www.oreillynet.com/pub/h/476 Encode Text for URLs
# http://evanjones.ca/python-utf8.html How to Use UTF-8 with Python
# http://abitno.linpie.com/a-small-translate-tool.html 寫了一個小小的翻譯工具
import sys
import os
from urllib import urlencode
import urllib2
import json

def get_json( uri ):
	response = urllib2.urlopen( uri )
	return response

def translate( text ):
	uri="http://www.ajax.googleapis.com/ajax/services/language/translate"
	query=urlencode( { 'v': '1.0', 'langpair': 'zh|en', 'q':
			text.encode('utf-8') } )
	uri = uri+"?"+query
	return json.load( get_json( uri ) )

text = unicode( sys.argv[1], "utf-8" )
print unicode( text ) + u" => " + translate( text )['responseData']['translatedText']
</pre>

		
		]]>
	</content:encoded>
	<link>http://blog.roodo.com/thinkingmore/archives/9964381.html</link>
	<guid>http://blog.roodo.com/thinkingmore/archives/9964381.html</guid>
	<category>Python</category>
	<pubDate>Tue, 15 Sep 2009 16:43:39 +0800</pubDate>
</item>
</channel>
</rss>