Code examples
Here are provided some examples of files parsing code for the most common usecases
Get translations in <surah, ayah [, word], text> format
The most common way to use a translation is to get it in csv-like format, i.e. like <surah, ayah, text>
(or <surah, ayah, word, text>
for word-by-word translations) format. To do so, one can easily read a JSON translation file:
import json
# Read the json translation-file
with open(path_to_json_file, "r") as translation_file:
translation = json.load(translation_file)
# Loop over surahs-ayahs-words
for surah in translation["content"]["surahs"]:
for ayah in surah["ayahs"]:
print(surah["number"], ayah["number"], ayah["text"]) # Put your code here
# For a word-by-word translation add one more loop:
#for word in ayah["words"]:
# print(surah["number"], ayah["number"], word["number"], word["text"])
You can do the same, using XML formatting.
from xml.etree import ElementTree as ET
# Read the XML translation-file
translation = ET.parse(path_to_xml_file).getroot()
# Loop over surahs-ayahs-words
for surah in translation.findall("content/surahs/surah"):
for ayah in surah.findall("ayahs/ayah"):
print(surah.attrib["number"], ayah.attrib["number"], ayah.text) # Put your code here
# For a word-by-word translation add one more loop:
#for word in ayah.findall("words/word"):
# print(surah.attrib["number"], ayah.attrib["number"], word.attrib["number"], word.text)
Get meta information
Here are some examples how one can read meta-data from the files
# Choose the language: en - for English, and native - for native
language = "en"
# Get the name of the translation
translation_json["meta"]["name"][language]
translation_xml.find(f"meta/name/{language}").text
# Get authors names
[author["name"][language] for author in translation_json["meta"]["authors"]]
[name.text for name in translation_xml.findall(f"meta/authors/author/name/{language}")]
# Get surah names. Change `names` to `nameTrnaliterated` for transliterated names
[surah["name"] for surah in translation_json["content"]["surahs"]]
[name.text for name in translation_xml.findall("content/surahs/surah/name")]
Last updated
Was this helpful?