Unicode encoding error with Python rdflib output

522 views Asked by At

I am using rdflib to parse CommonCrawl microdata. It is a big N-Quads format file. Everything is fine except the very last stage of saving to a CSV file or printing to the terminal, as it fails with encoding errors.

My current code is:

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 ])

This runs through many 1000s of the rows, but breaks at a certain point.

The error is:

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

Now, I have tried several things:

 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')

etc etc

The ctx[3] data is in the following format:

<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'].

The code above works in many cases, correctly extracting the URL and writing it to CSV, but it breaks inevitably on some data.

How do I properly get the text content from RDFlib? How can I find out what encoding format it is in? Is there another way to get text content out?

0

There are 0 answers