要使用 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)