DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> XML學習教程 >> XML詳解
Thinking XML:用 XML WordNet 服務器強化搜尋引擎
編輯:XML詳解     

前一階段我們介紹了 WordNet 自然語言資料庫,示範如何用 XML 表示它的節點,並透過 Web 提供這些 XML 文件。本文要談兩件事:如何把這套 XML 轉換成 RDF 表示,以及如何用 WordNet XML 服務器替搜尋引擎加上一層自然語言能力。

之所以把 WordNet 拉進 Thinking XML 的討論,是因為兩者剛好互補:XML 談的是資料的語意標記,WordNet 則提供自然語言本身語意的一種粗略模型。說「粗略」並無貶意——數千年來的語言哲學已說明,要為自然語言建立嚴格意義上的模型極其困難,甚至不可能。而在既有的 Web 建模方案裡,RDF 是最廣泛被採用的一套,因此用 RDF 為這套 WordNet XML 系統做個收尾,再合適不過。

從 XML 出發產生 RDF

先看單字「selection」的第一個同義詞集(synset)在 XML 下的樣子:

<?XML version="1.0" encoding="UTF-8"?>
<noun XML:id="152253">
  <gloss>the act of choosing or selecting; "your choice of colors was
   unfortunate"; "you can take your pick"</gloss>
  <word-form>choice</word-form>
  <word-form>selection</word-form>
  <word-form>option</word-form>
  <word-form>pick</word-form>
  <hypernym part-of-speech="noun" target="32816"/>
  <frames part-of-speech="verb" target="653781"/>
  <frames part-of-speech="verb" target="656613"/>
  <frames part-of-speech="verb" target="652154"/>
  <hyponym part-of-speech="noun" target="152613"/>
  <hyponym part-of-speech="noun" target="152749"/>
  <hyponym part-of-speech="noun" target="152898"/>
  <hyponym part-of-speech="noun" target="153642"/>
  <hyponym part-of-speech="noun" target="154057"/>
  <hyponym part-of-speech="noun" target="170871"/>
  <hyponym part-of-speech="noun" target="173378"/>
</noun>

最困難的一步是決定採用哪一套 RDF 模式。社群圍繞 WordNet 的 RDF 表示已有不少成果,最近的官方研究是 W3C 在 2004 年中期發布的「Wordnet in RDFS and OWL」初步草案。這項工作還遠未完成,包含智利研究者 Alvaro Graves 在內的一些人正在持續改進它。這裡我採用一種輕量的 RDF/XML 表示,與 W3C 的研究方向相容,但不牽入其中仍待收斂的部分:

<?XML version="1.0" encoding="UTF-8"?>
<rdf:RDF xmlns:wn="https://uche.ogbuji.Net/tech/rdf/wordnet/"
         xmlns:rdf="https://www.w3.org/1999/02/22-rdf-syntax-ns#">
  <wn:SynSet rdf:about="noun/152253">
    <wn:glossaryEntry>
      the act of choosing or selecting; "your choice of colors was unfortunate";
      "you can take your pick"
    </wn:glossaryEntry>
    <wn:wordForm>choice</wn:wordForm>
    <wn:wordForm>selection</wn:wordForm>
    <wn:wordForm>option</wn:wordForm>
    <wn:wordForm>pick</wn:wordForm>
    <wn:hypernym rdf:resource="noun/32816"/>
    <wn:frames rdf:resource="verb/653781"/>
    <wn:frames rdf:resource="verb/656613"/>
    <wn:frames rdf:resource="verb/652154"/>
    <wn:hyponym rdf:resource="noun/152613"/>
    <wn:hyponym rdf:resource="noun/152749"/>
    <wn:hyponym rdf:resource="noun/152898"/>
    <wn:hyponym rdf:resource="noun/153642"/>
    <wn:hyponym rdf:resource="noun/154057"/>
    <wn:hyponym rdf:resource="noun/170871"/>
    <wn:hyponym rdf:resource="noun/173378"/>
  </wn:SynSet>
</rdf:RDF>

W3C 當時尚未為 RDF 表現在的 WordNet 定下命名空間,因此暫用 https://uche.ogbuji.Net/tech/rdf/wordnet/。同義詞集之間的指標關係沿用 WordNet 指針的名字(hypernym、frames 等)。W3C 工作小組似乎傾向專用的屬性名(如 hypernymOf),我對此持保留意見:WordNet 每建立一種新的指針關係,就得回頭修訂一次模式,維護成本太高。

轉換:用 XSLT 把 XML 變成 RDF/XML

我一直很有興趣的一件事是:XML 本身能在多大程度上直接作為 RDF 模型的來源格式,而不必依賴繁瑣的 RDF/XML 寫法。最可行的路徑是用 XSLT 把 XML 轉成 RDF/XML,再載入 RDF 模型;理想情況下甚至可以用 4Suite 這類工具,完全不必理會中間的 RDF/XML 文字檔。既然目標格式已定,剩下的就是一份轉換樣式表:

<?XML version="1.0" encoding="utf-8"?>
<xsl:transform version="1.0"
               xmlns:xsl="https://www.w3.org/1999/XSL/Transform"
               xmlns:rdf="https://www.w3.org/1999/02/22-rdf-syntax-ns#"
               xmlns:wn="https://uche.ogbuji.Net/tech/rdf/wordnet/"
               XML:base="https://uche.ogbuji.Net/tech/rdf/wordnet/">
  <xsl:output indent="yes"/>

  <xsl:template match="/">
    <rdf:RDF>
      <xsl:apply-templates/>
    </rdf:RDF>
  </xsl:template>

  <xsl:template match="noun|verb|adjective|adverb">
    <wn:SynSet rdf:about="{name()}/{@XML:id}">
      <xsl:apply-templates/>
    </wn:SynSet>
  </xsl:template>

  <xsl:template match="gloss">
    <wn:glossaryEntry><xsl:copy-of select="node()"/></wn:glossaryEntry>
  </xsl:template>

  <xsl:template match="word-form">
    <wn:wordForm><xsl:value-of select="."/></wn:wordForm>
  </xsl:template>

  <xsl:template match="*">
    <xsl:element namespace="https://uche.ogbuji.Net/tech/rdf/wordnet/"
                 name="wn:{name()}">
      <xsl:attribute namespace="https://www.w3.org/1999/02/22-rdf-syntax-ns#"
                     name="rdf:resource">
        <xsl:value-of select="concat(@part-of-speech, '/', @target)"/>
      </xsl:attribute>
    </xsl:element>
  </xsl:template>
</xsl:transform>

給搜尋引擎加一層語意

目標很具體:給定一個查詢詞,我們希望搜尋能自動擴展到若干意義相關的詞。當使用者搜尋「selection」,系統應該也把含「vote」、「choice」、「ballot」的文件一起撈出來。做法是從查詢詞開始問 WordNet 服務器,然後沿著相關詞彙的指針遞迴往下問。本文把指針限定為下義詞(hyponym)——一般而言,就是指向表示更具體概念的詞彙。

這需要把前一階段的服務器程式細化一下:除了完整的詞形清單,WordNet 服務器也得能回傳原始的 XML 同義詞集。下面的 CherryPy 服務器在既有基礎上做了特化,讓你能從類似 https://localhost:8080/raw/pointer/noun/5955443 的 URL 取得原始同義詞集 XML:

import cherrypy
from picket import Picket, PicketFilter
from wnXMLlib import *

class root:
    _cpFilterList = [ PicketFilter(defaultStylesheet="viewWord.xslt") ]

class Wordform_handler:
    def __init__(self, applyxslt=False):
        self.applyxslt = applyxslt
        return

    @cherrypy.expose
    def default(self, word):
        synsets = serialized_synsets_for_word(word)
        result = ''.join(synsets)  # Concatenate strings in result list
        # Wrap up the XML fragments into a full document
        wordXML = '<word-senses text="' + word + '">' + result + '</word-senses>'
        if self.applyxslt:
            picket = Picket()
            picket.document = wordXML
            return picket  # apply the XSLT and return the result
        return wordXML

class pointer_handler:
    def __init__(self, applyxslt=False):
        self.applyxslt = applyxslt
        return

    @cherrypy.expose
    def default(self, pos, target):
        synset = getSynset(pos, int(target))
        synsetXML = serialize_synset(synset)
        if self.applyxslt:
            picket = Picket()
            picket.document = synsetXML
            return picket  # apply the XSLT and return the result
        return synsetXML

cherrypy.root = root()
cherrypy.root.view = Wordform_handler(applyxslt=True)
cherrypy.root.raw = Wordform_handler()
cherrypy.root.raw.pointer = pointer_handler()
cherrypy.root.pointer = pointer_handler(applyxslt=True)
# Disable debugging messages in Web responses
cherrypy.config.update({'logDebugInfoFilter.on': False})
cherrypy.server.start()

接著是客戶端。這支程式接受一個單字,用 Python 集合收集整條下義詞鏈並去除重複:

import sets
import urllib
from Ft.XML import Parse

BASEURI = 'https://localhost:8080/'

def get_hyponym_chain(word):
    '''
    returns a set with all the hyponyms of a word, the hyponyms
    of those hyponyms, and so on, recursively
    '''
    accumulator = []  # Storage list for the hyponym chain

    def process(xml):
        '''
        extract the hyponym chain from a DOM node. Common processing for
        word-form and synset XML
        '''
        hyponyms = xml.xpath(u'//hyponym')
        wforms = [e.xpath(u'string()') for e in xml.xpath(u'//word-form')]
        accumulator.extend(wforms)
        for hyponym in hyponyms:
            pos = hyponym.xpath(u'string(@part-of-speech)')
            target = hyponym.xpath(u'string(@target)')
            expand_hyponyms(pos, target, accumulator)
        return

    def expand_hyponyms(pos, target, accumulator):
        '''
        follow a pointer and extract the hyponym chain from the resulting XML
        '''
        synsetXML = Parse(BASEURI + 'raw/pointer/' + pos + '/' + target)
        process(synsetXML)
        return

    # escape any spaces or other problem characters in the word
    word = urllib.quote(word)
    wordXML = Parse(BASEURI + 'raw/' + word)
    process(wordXML)
    return sets.Set(accumulator)  # eliminate dupes

if __name__ == '__main__':
    # If invoked from the command line, get the hyponym chain from the
    # word given in the command-line parameters
    import sys
    print get_hyponym_chain(' '.join(sys.argv[1:]))

記得依實際部署調整 BASEURI。以「selection」為參數執行,會得到一組 Unicode 字串(以下為便於閱讀略作排版):

Set([u'selection', u'move', u'co-option', u'cut', u'secret ballot',
     u'manoeuvre', u'juke', u'casting', u'survival', u'Haftarah', u'choice',
     u'cutting', u'safe harbor', u'suicide pill', u'shark repellent',
     u'scorched-earth policy', u'designation', u'delegacy', u'casting vote',
     u'press cutting', u'demarche', u'epigraph', u'security', u'balloting',
     u'precaution', u'tactical maneuver', u'fast one', u'split ticket',
     u'clipping', u'stratified sampling', u'artifice', u'excerpt', u'greenmail',
     u'election', u'parking', u'naming', u'write-in', u'extract', u'recognition',
     u'pocket veto', u'survival of the fittest', u'decision', u'track', u'quote',
     u'schtik', u'maneuver', u'analecta', u'veto', u'citation', u'analects',
     u'step', u'representative sampling', u'favorite', u'colouration',
     u'sortition', u'drawing lots', u'pick', u'gambit', u'stratagem',
     u'misquotation', u'cumulative vote', u'sampling', u'guard', u'laying on of
     hands', u'fake', u'vote', u'gimmick', u'countermine', u'ploy', u'intention',
     u'willing', u'call', u'lucky dip', u'way', u'footwork', u'option',
     u'feint', u'determination', u'safeguard', u'security measures', u'quotation',
     u'press clipping', u'ruse', u'trick', u'porcupine provision', u'measure',
     u'straight ticket', u'twist', u'mimesis', u'appointment', u'volition',
     u'random sampling', u'ordinance', u'ballot', u'poison pill',
     u'pac-man strategy', u'proportional sampling', u'conclusion',
     u'multiple voting', u'golden parachute', u'favourite', u'assignment',
     u'block vote', u'device', u'nomination', u'coloration', u'casting lots',
     u'newspaper clipping', u'co-optation', u'ordination', u'natural selection',
     u'tactical manoeuvre', u'pleasure', u'voting', u'resolution',
     u'countermeasure'])

效能:為什麼這條路比較快

幾年前我曾用大型 RDF 資料庫做同義詞驅動的搜尋,效能問題嚴重:跑完「selection」及其下義詞要兩分多鐘。用現在的機器重跑,這種做法大約需要一分鐘。而改用本文的 WordNet XML 服務器方案,在同一台機器上不到一秒就完成——即使過程中包含數次本地 HTTP 請求。

原因在於 WordNet XML 服務器用的是 WordNet 資料庫自身的專用雜湊與索引,而不是對通用 RDF 資料庫下發大型查詢。它採取分而治之的策略,在很小的範圍內處理 XML,而非依賴單一的全域查詢。再強調一次:RDF 有時是不錯的資料模型,但對通用 DBMS 而言,它既非最可行的語法,也不是最佳的儲存形式。把「模型」與「儲存」分開思考,往往能找到快得多的實作。

結語

我們花了三篇文章,討論如何在 XML 與 RDF 應用程式中使用 WordNet 這個自然語言語意資料庫,本文是最後一篇,希望為動手實作的你準備了足夠的工具。普林斯頓大學的英文 WordNet 計畫是一項龐大的公共服務,至今仍在持續改進。可惜的是其他語言的類似研究出現得相當緩慢:2001 年啟動的 EuroWordNet 針對幾種歐洲語言做了相近的工作,但東亞及其他語系至今仍少見類似規模的計畫。如果你知道相關企畫,或對這個主題有別的想法,歡迎到 Thinking XML 討論區分享。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved