Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- # Filename: tabulate_wikidata_demo.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- This script demonstrates how to query the Wikidata endpoint for a given item ID and display the labels in tabular form using the tabulate library.
- Requirements:
- - Python 3.x
- - requests library: to send HTTP requests to the Wikidata endpoint
- - tabulate library: to format data into a table
- - types-tabulate: library stubs for static type checking with tabulate
- Functions:
- 1. query_wikidata_and_display_table(item_id='Q100924304'):
- Queries the Wikidata endpoint for the specified item ID (default: Q100924304).
- Retrieves the labels in various languages associated with the item and displays them in tabular form.
- Also adds an additional label "Jeoi" in English to demonstrate tabulate formatting.
- Usage:
- 1. Ensure that Python 3.x is installed on your system.
- 2. Install the required libraries using pip:
- ```
- pip install requests tabulate types-tabulate
- ```
- 3. Run the script using the following command:
- ```
- python tabulate_wikidata_demo.py
- ```
- Additional Notes:
- - This script makes use of the Wikidata Query Service (https://query.wikidata.org/) to fetch data.
- - The item ID used for demonstration purposes is "Jeoi" (Q100924304), which represents a Chinese given name.
- - The tabulate library is employed to format the retrieved data into a table for better visualization.
- - Demo messages are printed throughout the script to indicate the progress and execution steps.
- Expected Output Data:
- The script will display a table containing the labels associated with the item "Jeoi" in various languages, along with an additional label "Jeoi" in English.
- """
- import requests
- from tabulate import tabulate
- # Function to print divider lines
- def line():
- print("-" * 60)
- def print_demo(message):
- """Prints a message with DEMO prefix."""
- line()
- print("\n[DEMO] " + message)
- # line()
- print()
- def query_wikidata_and_display_table(item_id="Q100924304"):
- """Queries the Wikidata endpoint for a given item ID and displays the result in tabular form."""
- print_demo("Starting the demo script...")
- print_demo("Demo: Wikidata")
- print_demo(f"Querying Wikidata endpoint for item ID: ({item_id})")
- print_demo("Displaying table...")
- query = f"""
- SELECT
- (lang(?label) AS ?lang)
- ?label
- {{
- wd:{item_id} rdfs:label ?label .
- }}
- """
- response = requests.get(
- "https://query.wikidata.org/sparql",
- params={"query": query},
- headers={"Accept": "application/sparql-results+json"},
- )
- if response.status_code != 200:
- print_demo(f"Failed to query Wikidata. Status code: {response.status_code}")
- return
- response_json = response.json()
- if "results" not in response_json or "bindings" not in response_json["results"]:
- print_demo("Failed to parse Wikidata response.")
- return
- results = response_json["results"]["bindings"]
- # Extracting labels and languages from the response
- table_data = [
- (result["lang"]["value"], result["label"]["value"]) for result in results
- ]
- # Adding the Chinese given name 'Jeoi' as a label in Spanish
- for lang in ["es"]:
- table_data.append((lang, "Jeoi"))
- print(tabulate(table_data, headers=["Language", "Label"]))
- if __name__ == "__main__":
- query_wikidata_and_display_table()
- line()
- print("Demo script completed!")
- line()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement