我知道古腾堡(一家提供公共(public)领域书籍的公司)不允许自动访问他们的网站,但是他们确实为此目的以“机器可读格式”提供它们,特别是 RDF。我是新手,从未听说过这种格式,谷歌搜索也无济于事。我已经获得了 rdflib 模块,坦率地说,我不知道该怎么做。
我想做的是提取我认为可以通过我下载的 RDF 文件合法访问的文本。在 rdf 文件中,除其他外,还有这一行:
<dcterms:hasFormat rdf:resource="http://www.gutenberg.org/ebooks/100.txt.utf-8"/>
它指向带有本书文本文件的古腾堡页面,我假设程序可以从那里获取文本,但我不确定,因为我看不出直接抓取他们的网站和抓取之间的区别它通过 RDF 文件。
那么,如果文本完全可以通过编程方式访问,我该怎么做呢?
最佳答案
您不会在 RDF catalog from from Project Gutenberg 中找到全文.不过,它确实包含多种格式的文本 URL。下载 catalog zip file 后并解压缩它,下面是如何从特定的 RDF 文件中获取 HTML 图书 URL。
filename = 'cache/epub/78/pg78.rdf'
from lxml import etree
rdf = open(filename).read()
tree = etree.fromstring(rdf)
resource_tag = '{http://www.w3.org/1999/02/22-rdf-syntax-ns#}resource'
hasFormat_tag = './/{http://purl.org/dc/terms/}hasFormat'
resources = [el.attrib[resource_tag] for el in tree.findall(hasFormat_tag)]
urls = [url for url in resources if url.endswith('htm')]
// urls[0] is 'http://www.gutenberg.org/files/78/78-h/78-h.htm'
一旦您获得了所需图书的 HTML 版本的 URL,以下是获取文本的方法。
import requests
from lxml import etree
response = requests.get(urls[0])
html = etree.HTML(response.text)
text = '\n'.join([el.text for el in html.findall('.//p')])
text
现在包含 Tarzan 的全文,减去 Project Gutenberg 元数据、目录和章节标题。
>>> text[:100]
u'\r\nI had this story from one who had no business to tell it to me, or to\r\nany other. I may credit th'
请注意,古腾堡书籍之间存在不一致,因此您的结果可能会有所不同。
关于python-3.x - Python,读取 RDF 文件,抓取古腾堡书籍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19588952/