How do I add image url with graph add in rdflib - python

I am using rdflib==4.1.2.
This is my code
>>> g=rdflib.Graph()
>>> s=rdflib.BNode()
>>> FOAF = rdflib.Namespace("http://xmlns.com/foaf/0.1/")
>>> g.bind('foaf', FOAF)
>>> g.add((s, FOAF['img'],"https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcToZGEWvIBFgCiona6d74FtVthl4lkdJg3d61SGy-UCf4qFuDLD"))
I am getting this traceback.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/rdflib/graph.py", line 394, in add
"Object %s must be an rdflib term" % (o,)
AssertionError: Object https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcToZGEWvIBFgCiona6d74FtVthl4lkdJg3d61SGy-UCf4qFuDLD must be an rdflib term
How do I fix this?
Thanks!

The function Graph.add expects a tuple with three nodes as can be seen in the graph.py code:
assert isinstance(o, Node)
you can use URIRef to convert your last parameter into one (see also the examples of the documentation):
g.add((s, FOAF['img'],rdflib.URIRef("https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcToZGEWvIBFgCiona6d74FtVthl4lkdJg3d61SGy-UCf4qFuDLD")))

Related

Python Package addict force error if not existing

The package addict allows you to use dicts through attribute setting:
Example from the website:
from addict import Dict
body = Dict()
body.query.filtered.query.match.description = 'addictive'
body.query.filtered.filter.term.created_by = 'Mats'
Now when when I use for example a = body.B and I haven't included B yet it does not throw an error, but just returns nothing. How can I make it throw an error when the attribute was net yet set?
addict.Dict implements the __missing__ method to generate a value for any missing key(/attribute); the current implementation generates a new Dict instance. If you don't want this behaviour, you'll have to override it:
class MyDict(Dict):
def __missing__(self, name):
raise KeyError(name)
Note that this will throw a KeyError for attribute access, which may be confusing; you could also override __getattr__ if you want to throw an AttributeError instead. In use:
>>> body = MyDict()
>>> body.B
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "path/to/addict.py", line 62, in __getattr__
return self.__getitem__(item)
File "<stdin>", line 3, in __missing__
KeyError: 'B'
>>> body.B = "hello"
>>> body.B
'hello'
Note also that this will break the other examples you showed as well, as e.g. foo.bar.baz = qux calls __getattr__ on foo before calling __setattr__ on foo.bar (if successful):
>>> body.query.filtered.query.match.description = 'addictive'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "path/to/addict.py", line 62, in __getattr__
return self.__getitem__(item)
File "<stdin>", line 3, in __missing__
KeyError: 'query'

How can I recover data from a possibly corrupt, or too large Python Shelve db?

I've been using Shelve as a document store.
The key is a stringified integer and the value is just some html in a string. Unfortunately my script ended up putting so many entries in the db that errors occurred (I don't have the exact ones to hand). The db is about 36GB in size and now when I load it and then try and iterate on the keys or anything like that I get the following error...
import shelve
db = shelve.open("my.shelf")
ks = db.keys()
for k in ks: print(k)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/_collections_abc.py", line 482, in __iter__
yield from self._mapping
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/shelve.py", line 95, in __iter__
for k in self.dict.keys():
SystemError: Negative size passed to PyBytes_FromStringAndSize
>>> list(ks.__dict__.values())[0].dict
<_dbm.dbm object at 0x10037ef90>
>>> help(list(ks.__dict__.values())[0].dict)
>>> list(ks.__dict__.values())[0].dict.keys()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
SystemError: Negative size passed to PyBytes_FromStringAndSize
This is on OSX Yosemite. Python 3.4
Any way to repair this or get the keys and values out for placement in a more appropriate store?
You must know key names whose corresponding objects were successfully stored.
Because a failure at saving data object would corrupt your db.
Then,
db = shelve.open("my.shelf")
for key in list_of_successfully_saved_obj's_name:
val = db.get(key)
...

how to use python help to file functions

If I want to see the str.replace() function: help(str.replace)
the result is:
Help on method_descriptor:
replace(...)
S.replace(old, new[, count]) -> str
Return a copy of S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
(END)
but how use help file.read or readlines?
for example, help(file.read) and help(read) are both errors:
>>> help(file)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'file' is not defined
>>> help(file.read)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'file' is not defined
>>> help(read)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'read' is not defined
How can I use help see file functions?
The file type has been removed from Python 3. Look at the io module instead:
>>> import io
>>> help(io.TextIOBase.read)
Help on method_descriptor:
read(...)
Read at most n characters from stream.
Read from underlying buffer until we have n characters or we hit EOF.
If n is negative or omitted, read until EOF.

Is there a shortcut for self.assertNotEqual() in nose?

_eq seems to be the equal to self.assertEqual()
But is there also a self.assertNotEqual() in nose?
Thanks
Nose doesn't have an equivalent to self.assertNotEqual(), but you can use all of the unittest.TestCase assert methods via nose.tools. They are renamed to all-lowercase and with underscores. For example:
>>> from nose.tools import assert_not_equal
>>> assert_not_equal(1, 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 518, in assertNotEqual
raise self.failureException(msg)
AssertionError: 1 == 1
More info here.

Validate expression/infix in python

How do I validate an expression/infix in python? Is it possible?
For example:
a-d*9
5-(a*0.3-d+(0.4-e))/k*5
(a-d*9)/(k-y-4.3*e)+(t-7*c)
If you want Python-style expressions, you can use the parser in the ast module and check for SyntaxError:
>>> ast.parse('5-(a*0.3-d+(0.4-e))/k*5')
<_ast.Module object at 0x7fc7bdd9e790>
>>> ast.parse('5-(a*0.3-d+(0.4-e))/k*')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/ast.py", line 37, in parse
return compile(expr, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 1
5-(a*0.3-d+(0.4-e))/k*
^
SyntaxError: unexpected EOF while parsing
Though that might parse much more than you actually need:
>>> ast.parse('def spam(): return "ham"')
<_ast.Module object at 0x7fc7bdd9e790>
so you might want to inspect the returned parse tree carefully.

Categories