"""
25.Extraction de modèle
Extrayez les noms de champs et les valeurs du modèle «informations de base» inclus dans l'article et stockez-les sous forme d'objet dictionnaire.
"""
import json
import re
import utils
def get_uk_text(path):
    with open(path) as f:
        for line in f:
            line_data = json.loads(line)
            if line_data["title"] == "Angleterre":
                data = line_data
                break
    return data["text"]
uk_text = get_uk_text("jawiki-country.json")
# See uk_text.txt
# ans24
def get_basic_info(string: str) -> str:
    """Get basic information section
    """
    pattern = re.compile(
        r"""
            ^\{\{Informations de base.*?$   # '{{Informations de base'Lignes commençant par
            (.*?)       #Capturer la cible, n'importe quel 0 caractère ou plus, non gourmand
            ^\}\}$      # '}}'Lignes se terminant par
        """,
        re.MULTILINE | re.DOTALL | re.VERBOSE,
    )
    return re.findall(pattern, string)[0]
def get_content(string: str) -> list:
    r"""
    https://docs.python.org/3/library/re.html#regular-expression-syntax
    RE:
        - re.X (re.VERBOSE)     Allow us add command to explain the regular expression
        - re.M (re.MULTILINE)   Apply match to each line. If not specified, only match the first line.
        - re.S (re.DOTALL)      Allow to recognize '\n'
        - ^\|       String begin with |
        - ?         Causes the resulting RE to match 0 or 1 repetitions
        - *?        The '*' qualifier is greedy.
                    Adding ? after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched.
                    e.g. <.*> is matched against '<a> b <c>'
                    e.g. <.*?> will match only '<a>'
        - (...)     Matches whatever regular expression is inside the parentheses,
        - (?=...)   Matches if ... matches next, but doesn’t consume any of the string. This is called a lookahead assertion.
                    For example, Isaac (?=Asimov) will match 'Isaac ' only if it’s followed by 'Asimov'.
        - (?:...)   A non-capturing version of regular parentheses.
    Input:
        - '|Lien de l'emblème national=([[Emblème national britannique|emblème national]])'
    Return:
        - {"Lien de l'emblème national": "([[Emblème national britannique|emblème national]])"}
    """
    pattern = re.compile(
        r"""
            ^\|         # '|'Lignes commençant par
            (.+?)       #Cible de capture (nom du champ), un ou plusieurs caractères, non gourmand
            \s*         #0 ou plusieurs caractères vides
            =
            \s*         #0 ou plusieurs caractères vides
            (.+?)       #Capturer la cible (valeur), un ou plusieurs caractères, non gourmand
            (?:         #Démarrer un groupe qui n'est pas capturé
                (?=\n\|)    #nouvelle ligne+'|'Avant (anticipation affirmative)
                |           #Ou
                (?=\n$)     #nouvelle ligne+Avant la fin (anticipation affirmative)
            )               #Fin du groupe
            """,
        re.MULTILINE | re.DOTALL | re.VERBOSE,
    )
    result = re.findall(pattern, string)
    return {k: v for k, v in result}  # dict is ordered due to python 3.7
basic_info = get_basic_info(uk_text)
# print(basic_info[-100:])
# |Numéro de téléphone international= 44
# |Remarque= <references/>
result = get_content(basic_info)
utils.save_json(result, "25_en_basic_info.json")
for r in result.items():
    print(r)
# ('Nom abrégé', 'Angleterre')
# ('Nom du pays japonais', 'Royaume-Uni de Grande-Bretagne et d'Irlande du Nord')
# ...
# ('Numéro de téléphone international', '44')
# ('Remarque', '<references/>')
        Recommended Posts