Advertisement
Python253

tabulate_wikidata_demo

May 3rd, 2024
963
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.53 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: tabulate_wikidata_demo.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. 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.
  9.  
  10. Requirements:
  11. - Python 3.x
  12. - requests library: to send HTTP requests to the Wikidata endpoint
  13. - tabulate library: to format data into a table
  14. - types-tabulate: library stubs for static type checking with tabulate
  15.  
  16. Functions:
  17. 1. query_wikidata_and_display_table(item_id='Q100924304'):
  18.    Queries the Wikidata endpoint for the specified item ID (default: Q100924304).
  19.    Retrieves the labels in various languages associated with the item and displays them in tabular form.
  20.    Also adds an additional label "Jeoi" in English to demonstrate tabulate formatting.
  21.  
  22. Usage:
  23. 1. Ensure that Python 3.x is installed on your system.
  24. 2. Install the required libraries using pip:
  25.    ```
  26.    pip install requests tabulate types-tabulate
  27.    ```
  28. 3. Run the script using the following command:
  29.    ```
  30.    python tabulate_wikidata_demo.py
  31.    ```
  32.  
  33. Additional Notes:
  34. - This script makes use of the Wikidata Query Service (https://query.wikidata.org/) to fetch data.
  35. - The item ID used for demonstration purposes is "Jeoi" (Q100924304), which represents a Chinese given name.
  36. - The tabulate library is employed to format the retrieved data into a table for better visualization.
  37. - Demo messages are printed throughout the script to indicate the progress and execution steps.
  38.  
  39. Expected Output Data:
  40. 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.
  41. """
  42.  
  43. import requests
  44. from tabulate import tabulate
  45.  
  46. # Function to print divider lines
  47. def line():
  48.     print("-" * 60)
  49.  
  50.  
  51. def print_demo(message):
  52.     """Prints a message with DEMO prefix."""
  53.     line()
  54.     print("\n[DEMO] " + message)
  55.     # line()
  56.     print()
  57.  
  58.  
  59. def query_wikidata_and_display_table(item_id="Q100924304"):
  60.     """Queries the Wikidata endpoint for a given item ID and displays the result in tabular form."""
  61.     print_demo("Starting the demo script...")
  62.     print_demo("Demo: Wikidata")
  63.     print_demo(f"Querying Wikidata endpoint for item ID: ({item_id})")
  64.     print_demo("Displaying table...")
  65.     query = f"""
  66.    SELECT
  67.      (lang(?label) AS ?lang)
  68.       ?label
  69.    {{
  70.       wd:{item_id}  rdfs:label ?label .
  71.    }}
  72.    """
  73.     response = requests.get(
  74.         "https://query.wikidata.org/sparql",
  75.         params={"query": query},
  76.         headers={"Accept": "application/sparql-results+json"},
  77.     )
  78.     if response.status_code != 200:
  79.         print_demo(f"Failed to query Wikidata. Status code: {response.status_code}")
  80.         return
  81.  
  82.     response_json = response.json()
  83.     if "results" not in response_json or "bindings" not in response_json["results"]:
  84.         print_demo("Failed to parse Wikidata response.")
  85.         return
  86.  
  87.     results = response_json["results"]["bindings"]
  88.  
  89.     # Extracting labels and languages from the response
  90.     table_data = [
  91.         (result["lang"]["value"], result["label"]["value"]) for result in results
  92.     ]
  93.  
  94.     # Adding the Chinese given name 'Jeoi' as a label in Spanish
  95.     for lang in ["es"]:
  96.         table_data.append((lang, "Jeoi"))
  97.  
  98.     print(tabulate(table_data, headers=["Language", "Label"]))
  99.  
  100.  
  101. if __name__ == "__main__":
  102.     query_wikidata_and_display_table()
  103.     line()
  104.     print("Demo script completed!")
  105.     line()
  106.  
  107.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement