1

我正在用python构建一个搜索引擎。

我听说 Google 从 ODP(开放目录项目)中获取页面描述,以防 Google 无法使用页面中的元数据找出描述……我想做类似的事情。

ODP 是来自 Mozilla 的在线目录,其中包含网络上的页面描述,因此我想从 ODP 获取搜索结果的描述。如何从 ODP 获取特定 url 的准确描述,并在找不到时返回 python 类型“None”(这意味着 ODP 不知道我在寻找哪个页面)?

PS。有一个名为http://dmoz.org/search?q=Your+Search+Params的网址,但我不知道如何从那里提取信息。

4

1 回答 1

4

要使用 ODP 数据,您需要下载 RDF 数据转储。RDF 是一种 XML 格式;您将索引该转储以将 url 映射到描述;我会为此使用 SQL 数据库。

请注意,URL 可以出现在转储中的多个位置。例如,堆栈溢出列出了两次。谷歌使用这个条目中的文本作为站点描述,Bing 使用这个代替

数据转储当然相当大。在向数据库添加条目时,使用诸如 ElementTreeiterparse()方法之类的合理工具迭代地解析数据集。你真的只需要寻找<ExternalPage>元素,在下面获取<d:Title><d:Description>条目。

使用lxml(更快、更完整的 ElementTree 实现)看起来像:

from lxml import etree as ET
import gzip
import sqlite3

conn = sqlite3.connect('/path/to/database')

# create table
with conn:
    cursor = conn.cursor()
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS odp_urls 
        (url text primary key, title text, description text)''')

count = 0
nsmap = {'d': 'http://purl.org/dc/elements/1.0/'}
with gzip.open('content.rdf.u8.gz', 'rb') as content, conn:
    cursor = conn.cursor()
    for event, element in ET.iterparse(content, tag='{http://dmoz.org/rdf/}ExternalPage'):
        url = element.attrib['about']
        title = element.xpath('d:Title/text()', namespaces=nsmap)
        description = element.xpath('d:Description/text()', namespaces=nsmap)
        title, description = title and title[0] or '', description and description[0] or ''

        # no longer need this, remove from memory again, as well as any preceding siblings
        elem.clear()
        while elem.getprevious() is not None:
            del elem.getparent()[0]

        cursor.execute('INSERT OR REPLACE INTO odp_urls VALUES (?, ?, ?)',
            (url, title, description))
        count += 1
        if count % 1000 == 0:
            print 'Processed {} items'.format(count)
于 2013-05-03T09:20:34.133 回答