使用rdflib执行SPARQL查询时遇Unknown namespace prefix: weather错误
Let's break down what's happening here and how to fix it:
Why the Error Occurs
The error Exception: Unknown namespace prefix : weather pops up because your SPARQL query uses the weather: prefix, but rdflib has no clue what actual URI this prefix maps to. Even though your RDFa file probably defines this prefix (like prefix="weather: http://your-namespace-uri-here"), rdflib doesn't automatically carry that prefix mapping over to SPARQL queries unless you explicitly tell it to.
Your res1 works fine because it's just serializing the graph data you parsed—all the namespace info is already in the graph, so serialization doesn't need explicit prefix bindings for output. But SPARQL queries require clear prefix-to-URI mappings to resolve terms like weather:region.
What's Missing
You're missing a step to bind the weather prefix to its corresponding namespace URI in the context of your SPARQL query. rdflib's query engine can't guess what URI weather: refers to, so you have to provide that mapping explicitly.
How to Fix It
You have a few straightforward options to resolve this:
Option 1: Use the Full URI in the Query
Replace the weather:region prefix with the complete namespace URI for the region predicate. For example, if your RDFa defines weather: as http://example.org/weather#, your query becomes:
res2 = g.query("""SELECT ?obj WHERE { <http://localhost:8085/weather-2.html> <http://example.org/weather#region> ?obj . } """)
Note: You'll need to replace http://example.org/weather# with the actual namespace URI from your RDFa file.
Option 2: Bind the Prefix in the Query Call
Use the initNs parameter when calling g.query() to pass a dictionary of prefix-to-URI mappings:
res2 = g.query( """SELECT ?obj WHERE { <http://localhost:8085/weather-2.html> weather:region ?obj . } """, initNs={"weather": "http://example.org/weather#"} # Match this to your RDFa's weather prefix URI )
This tells rdflib exactly what weather: means for this specific query.
Option 3: Bind the Prefix to the Graph Globally
If you plan to use the weather prefix in multiple queries, bind it directly to your graph's namespace manager once:
from rdflib import Namespace # Bind the prefix to the graph weather_ns = Namespace("http://example.org/weather#") g.bind("weather", weather_ns) # Now your original query will work res2 = g.query("""SELECT ?obj WHERE { <http://localhost:8085/weather-2.html> weather:region ?obj . } """)
This makes the weather prefix available for all subsequent queries on this graph.
Quick Check
Before implementing any fix, double-check your weather-2.html RDFa source to find the exact namespace URI associated with the weather prefix. Look for something like:
<html prefix="weather: http://your-actual-weather-namespace-uri/">
Use that URI in whichever fix method you choose.
内容的提问来源于stack exchange,提问作者Ovaflow

