2

rdflib用来解析CommonCrawl microdata。这是一个很大的 N-Quads 格式文件。除了保存到 CSV 文件或打印到终端的最后阶段,一切都很好,因为它因编码错误而失败。

我目前的代码是:

import csv
import rdflib
from rdflib import ConjunctiveGraph, URIRef, Namespace, RDF, BNode

g = rdflib.ConjunctiveGraph()
g.parse("nquads.nquads", format="nquads")

with open('list.csv', 'wb') as csvfile:
    csvwriter = csv.writer(csvfile, delimiter=',',
                            quotechar='"', quoting=csv.QUOTE_MINIMAL)
    csvwriter.writerow(['URL'])

    for ctx in q.quads:
        s = ctx[3]
        s = s[s.index("<") + 1:s.rindex(">")] # Gets URL between < and >
        csvwriter.writerow([ s ])

这贯穿了许多 1000 行,但在某个点中断。

错误是:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 62-63: ordinal not in range(128)

现在,我尝试了几件事:

 s = ctx[3].toPython()
 s = ctx[3].value()
 s = str(ctx[3])
 s = ctx[3].encode('utf-8')
 s = ctx[3].encode('utf-8', 'ignore')

等等等等

ctx[3]数据格式如下:

<http://www.serenabakessimplyfromscratch.com/2014/07/blueberry-cinnamon-swirl-crumb.html> a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label 'IOMemory'].
<http://www.seriouseats.com/recipes/2009/01/meat-lite-warm-winter-salad.html?ref=excerpt_readmore> a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label 'IOMemory'].
<http://www.grouprecipes.com/103118/broccoli-rice-casserole.html> a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label 'IOMemory'].
<http://www.grouprecipes.com/67612/asian-chicken-noodle-soup.html> a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label 'IOMemory'].
<http://www.grouprecipes.com/113715/bouillabaisse-style-fish-stew.html> a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label 'IOMemory'].
<http://www.drinksmixer.com/drink15xy188.html> a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label 'IOMemory'].

上面的代码在很多情况下都有效,可以正确提取 URL 并将其写入 CSV,但它不可避免地会在某些数据上中断。

如何从 RDFlib 正确获取文本内容?如何找出它的编码格式?还有其他方法可以获取文本内容吗?

4

0 回答 0