blog.Ring.idv.tw

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

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

3 comments on "N-gram.一個語言中立的斷詞方法"

  1. 1. 清爽小雨 說:

    你只說一半,切出來後要如何去做預測?這才是重點喔!

    2009-04-24 14:35:27

  2. 2. Shen 說:

    謝謝您的指教 ^^
    這部份就留給您分享嚕!

    2009-04-24 15:34:39

  3. 3. Pore 說:

    翻了这么多网页,就您写的最简明易懂,谢谢博主了!看到公式就晕了,呵呵。头一次知道了CJK了。多谢!

    2013-03-05 02:18:54

Leave a Comment

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

::: 搜尋 :::

::: 分類 :::

::: Ads :::

::: 最新文章 :::

::: 最新回應 :::

::: 訂閱 :::

Atom feed
Atom Comment