blog.Ring.idv.tw

2008 October

N-gram.一個語言中立的斷詞方法

N-gram」.常被用於自然語言處理的領域之中~ 尤其是用來處理「CJK」的斷詞~

假設我們從詞庫的方式來看~ 如果有一個中文句子為:「研究生活動中心」,用詞庫來斷詞的話~ 可能的結果會是「研究」、「生活」、「動」、「中心」,或者「研究生」、「活動」和「中心」,當然這完全看詞庫斷詞是如何設計的~ 不過這還有許多洐生性的問題~ 例如:CKIP只針對Big5編碼的文字,或是未知詞的處理等等~

所以「N-gram」針對「CJK」能保有完善的斷詞方式~ 如果以上述的例子而言,用bigram斷詞的結果則為:「研究」、「究生」、「生活」、「活動」、「動中」和「中心」

而「N-gram」就取決於「N」的大小~ unigram(n=1)、bigram(n=2)、trigram(n=3) 以此類推~

下述是筆者簡單寫的一個小程式:

def ngram(n,sentence):
	s = sentence.split()
	if n == 1:
		return s
	
	slen = len(s)
	if n > slen:
		raise Exception, "N > %s" % slen
	
	nlist = []
	for idx in range(n-1,slen):
		s1 = []
		for i in range(0,n):
			s1.insert(0,s[idx-i])
		
		delimiter = " "
		str = delimiter.join(s1)
		nlist.append(str.strip())
	
	return nlist
	
print ngram(2,"the cat is on the mat , while a dog is on the chair .")

Bigram的結果:

['the cat', 'cat is', 'is on', 'on the', 'the mat', 'mat ,', ', while', 'while a', 'a dog', 'dog is', 'is on', 'on the', 'the chair', 'chair .']

Trigram的結果:

['the cat is', 'cat is on', 'is on the', 'on the mat', 'the mat ,', 'mat , while', ', while a', 'while a dog', 'a dog is', 'dog is on', 'is on the', 'on the chair', 'the chair .']

以此類推~

2008-10-03 01:38:11 | Comments (3)

Python Server Pages - Fruit Suggest

今天處理了一台伺服器~ 整個給它重灌Debian 4.0r4~ 因為這台伺服器先前被SSH-Attack~ 所以連IP都被封鎖住~

所以千萬別認為裝了「SSH」就絕對安全~ 因為總是有「無聊」的人會利用工具來做「暴力字典攻擊法」想辦法入侵... 所以防火牆的設定是不可少的~ 真搞不懂為什麼有人那麼「無聊」..= ="(我時間都不夠用了~)

好了~ 這不是重點~ 這篇的重點在於測試一個「Python Web Application」~ 我給它的主題就叫做「Fruit Suggest」~ 從名稱來看就知道和「Google Suggest」脫離不了關係~

是的~ 這個範例會結合「Python Server Pages」、「SQLite3」、「YUI Ajax」、「Google Suggest」和「PSP Template」,並且在「Debian Linux」的環境下執行~

我想~ 用一個最實際的簡單案例就是最好的驗證!!

不過~ 一開始還遇到許多問題~ 由於「Debian 4.0r4」預設是安裝「Python 2.4.4」版本~ 但是~ 我想用最新的「Python2.5」來執行這樣的環境~ 畢竟它有整合了「SQLite」~

所以要處理解決「Python2.5」的環境~ 筆者採用自行編譯「mod_python」的方式來處理~ 所以捨棄apt安裝「libapache2-mod-python」的方式~

如果你也需要這樣的解決方案~ 請參考「Jason R Briggs · mod_python and python2.5」的說明~

Fruit Suggest

.htaccess

SetHandler mod_python
PythonHandler mod_python.publisher
PythonDebug On

<Files ~ "\.(gif|html|jpg|png|js|css)$">
   SetHandler default-handler
</Files>

index.html

<html>
<head>
<title>Fruit Suggest</title>
<script src="http://yui.yahooapis.com/2.5.2/build/yahoo/yahoo-min.js"></script>
<script src="http://yui.yahooapis.com/2.5.2/build/event/event-min.js"></script>
<script src="http://yui.yahooapis.com/2.5.2/build/connection/connection-min.js"></script>
<style type="text/css" media="screen">
			body {
				font: 11px arial;
			}
			.suggest_link {
				background-color: #FFFFFF;
				padding: 2px 6px 2px 6px;
			}
			.suggest_link_over {
				background-color: #3366CC;
				padding: 2px 6px 2px 6px;
			}
			#search_suggest {
				position: absolute; 
				background-color: #FFFFFF; 
				text-align: left; 
				border: 1px solid #000000;			
			}		
</style>
<script language="JavaScript" type="text/javascript" src="ajax_search.js"></script>
</head>
<body>
		<div style="width: 500px;">
		<h3>Fruit Suggest</h3>
			<form id="frmSearch">
				<input type="text" id="txtSearch" name="txtSearch" alt="Search Criteria" onkeyup="searchSuggest();" autocomplete="off" />
				<input type="submit" id="cmdSearch" name="cmdSearch" value="Search" alt="Run Search" /><br />
				<div id="search_suggest">
				</div>
			</form>
		</div>
</body>
</html>

ajax_search.js

function searchSuggest()
{
	var callback = {
		success: function(o)
		{
			var ss = document.getElementById('search_suggest')
			ss.innerHTML = '';
			var str = o.responseText.split("\n");
		
			for(i=0; i < str.length - 1; i++)
			{
                                if(str[i] != "")
                                {
                                        var suggest = '<div onmouseover="javascript:suggestOver(this);" ';
                                        suggest += 'onmouseout="javascript:suggestOut(this);" ';
                                        suggest += 'onclick="javascript:setSearch(this.innerHTML);" ';
                                        suggest += 'class="suggest_link">' + str[i] + '</div>';
                                        ss.innerHTML += suggest;
                                }

			}
		},
		failure: function(o)
		{
			alert("Ajax failed!");
		}
	}
	var str = escape(document.getElementById('txtSearch').value);
	var transaction = YAHOO.util.Connect.asyncRequest('GET', '/ajax/ajax/index?search=' + str, callback, null);
}

//Mouse over function
function suggestOver(div_value) {
	div_value.className = 'suggest_link_over';
}
//Mouse out function
function suggestOut(div_value) {
	div_value.className = 'suggest_link';
}
//Click function
function setSearch(value) {
	document.getElementById('txtSearch').value = value;
	document.getElementById('search_suggest').innerHTML = '';
}

ajax.py

from mod_python import apache, psp
from cgi import escape
import sqlite3

def index(req):
	req.content_type = 'text/html'
	template = psp.PSP(req, filename='suggest.tmpl')
	_uid = req.form.getfirst('search')
	_uid = escape(_uid)+'%'
	conn = sqlite3.connect('/var/www/ajax/data.dat')
	c = conn.cursor()
	c.execute('select name from fruit where name like :who', {"who": _uid})
	res = c.fetchall()
	template.run({'search':res})

suggest.tmpl

<%
for f in search:
%>
<%=f[0]%>
<%
%>

data.dat (sqlite)

Fruit table的結構如下:

create table fruit(
	id int,
	name varchar
)

insert into fruit values (1,'apple')

Fruit Suggest 範例下載

Fruit Suggest.zip

參考資源

打造屬於你自己的Google Suggest!

2008-10-02 02:55:52 | Comments (2)

Python Server Pages - SQLite3

由於自從Python 2.5推出之後,它就內含了「SQLite (lightweight disk-based database)」,它是一個C library~ 所以有相當多的平台都將它當作內部的儲存方式,好比如:Google Android、Adobe AIR、Google Gears..

所以這篇主要記錄一些簡單的操作~ 感覺有點像一般小型ASP+Access網站的架構模式~

範例如下:

db.py

from mod_python import apache, psp
import sqlite3

def index(req):
	req.content_type = 'text/html'
	conn = sqlite3.connect('data.dat')
	c = conn.cursor()

	c.execute('''
	create table members(
		id int,
		name varchar,
		login timestamp
	)
	''')
	 
	c.execute('''
	insert into members
	values (1,'jeff','2006-10-01')
	''')
	c.execute('''
	insert into members
	values (2,'angie','2006-10-02')
	''')
	c.execute('''
	insert into members
	values (3,'dylan','2006-10-03')
	''')
	
	conn.commit()
	c.execute('select * from members')
	res = c.fetchall()

	who = "jeff"
	c.execute("select id,name,login from members where name=:who", {"who": who})
	jeff = c.fetchone()

	template = psp.PSP(req, filename='db.tmpl')
	template.run({'results':res,'jeff':jeff})

db.tmpl

<html>
<p><%=jeff%></p>
<%
for f in results:
%>
<%=f[0]%><%=f[1]%><%=f[2]%><br/>
<%
%>
</html>

相關資源

sqlite3 -- DB-API 2.0 interface for SQLite databases

2008-10-01 02:36:50 | Add Comment

Python Server Pages - Nested PSP Templates

在上一篇「Python Server Pages - Forms」已經簡單的記錄一下「Form」的處理~

而這篇則是針對如果我們想在同一份頁面中~ 分離多個「Template」來進行處理~ 它就稱作「Nested PSP Templates」。

我們仍然以上一篇文章的例子來作解釋以方便理解。

Nested PSP Templates

「form.html」不需要變動到它,只要更動「index.py」和相關的「templates」即可。

index.py

from mod_python import apache, psp

def index(req,userid,fruit):
	req.content_type = 'text/html'
	uid_temp = psp.PSP(req, filename='uid.tmpl',vars = {'uid':userid})
	fruit_temp = psp.PSP(req, filename='fruit.tmpl')
	fruit_temp.run({'fruit':fruit,'uid_temp':uid_temp})

從這個例子可以發現,我們同時使用到「uid.tmpl」和「fruit.tmpl」來處理同一份頁面。

uid.tmpl

<h1>Hello, <%=uid%></h1>

fruit.tmpl

<html>
<%=uid_temp%>
<%
for f in fruit:
%>
<%=f%>
<%
%>
</html>

在這個範例上,整個重點就在於「uid_temp」已經優先被剖析和編譯了,直到執行「fruit_temp.run()」時才會整個傳送到Client端~

相關資源

4.9 psp - Python Server Pages

2008-10-01 01:43:01 | Add Comment

Python Server Pages - Forms

先前筆者有寫了一篇簡單的PSP(Python Server Pages)介紹「Python Server Pages - 架構一個PSP環境」,不過那篇是針對「Windows」環境下的設置~ 如果我們要在「Linux」的環境下Run的話~ 同樣地~ 安裝「libapache2-mod-python」即可。(請注意:Debian 4.0r4 預設是Python2.4,若你要安裝Python2.5請參考「Jason R Briggs · mod_python and python2.5」)

如下:

apt-get install libapache2-mod-python

且先前的「Hello World」範例就直接用「Templating System」來實作了~ 因為透過「templating mechanism」可以幫助我們將「Business Logic」和「Presentation」來做個分離~ 以後在維護上就會較方便,且容易除錯~

而這篇主要來記錄PSP是如何處理「Form」,就直接看下述範例:

Python Server Pages - Forms

如同先前所介紹的,這邊我們仍然以「psp」的目錄來測試。

.htaccess

SetHandler mod_python
PythonHandler mod_python.publisher
PythonDebug On

<Files ~ "\.(gif|html|jpg|png)$">
   SetHandler default-handler
</Files>

form.html

<html>
<body>
<form action="/psp/" method="post">
<p>UserID: <input type="text" name="userid">
<br/>
<input type="checkbox" name="fruit" value="apple">Apple
<input type="checkbox" name="fruit" value="banana">Banana
<input type="checkbox" name="fruit" value="grape">Grape
<input type="submit" value="Submit"></p>
</form>
</body>
</html>

index.py

from mod_python import apache, psp
from cgi import escape

def index(req):
	req.content_type = 'text/html'
	template = psp.PSP(req, filename='hello.tmpl')
	_fruit = req.form.getlist('fruit')
	_fruit = map(lambda fruit: escape(fruit), _fruit)
	_uid = req.form.getfirst('userid')
	_uid = escape(_uid)
	template.run({'uid':_uid,'fruit':_fruit})

hello.tmpl

<html>
	<h1>Hello, <%=uid%></h1>
<%
for f in fruit:
%>
<%=f%>
<%
%>
</html>

最後打開你的瀏覽器,輸入「http://localhost/psp/form.html」來測試~ 應該就沒啥問題了!

從這個例子我們可以知道說~ 要取得「Form」的資料必須透過「Request」這個物件裡面的「form」attribute來取得~

重點在於「form」attribute就是FieldStorage類別的instance,而它儲存了一份reference在「Request」物件中的「form」attribute

雖然我們可以透過「FieldStorage」來取得「Form」的資料~ 但其實還有更快的方式~

我們可以直接利用定義函式中所要傳入的參數來對應即可~ 如下所示:

def index(req,userid,fruit):
.....

只要參數名稱對應「Form」的欄位名稱即可。

2008-10-01 01:17:11 | Add Comment

Next Posts
Copyright (C) Ching-Shen Chen. All rights reserved.

::: 搜尋 :::

::: 分類 :::

::: 最新文章 :::

::: 最新回應 :::

::: 訂閱 :::

Atom feed
Atom Comment