Commit 041247d8 authored by Mathieu Goux's avatar Mathieu Goux
Browse files

Tools

Add python scripts
parent 29160746
Loading
Loading
Loading
Loading
+84 −0
Original line number Diff line number Diff line
%% Cell type:code id:ab500074 tags:

``` python
#Script Python qui récupère les attributs des tokens et les dispose dans un tableur, pour vérification des erreurs.
```

%% Cell type:code id:39314c86 tags:

``` python
#On renseigne les chemins des fichiers

path_in = ""
path_out = ""
```

%% Cell type:code id:2c015097 tags:

``` python
import xml.etree.ElementTree as ET
import re

liste = []

    # On ouvre le fichier d'entrée

with open(path_in, encoding="utf8") as xml:

    # On importe le XML-TEI d'entrée et on le lit.
    tree = ET.parse(path_in)
    root = tree.getroot()

        #On boucle sur les balises w en reprenant la hiérarchie

        # Book

    for book in root.findall('.//div[@type="book"]'):
        book_nb = book.get('n')

                # Chapter

        for chapter in book.findall('.//div[@type="chapter"]'):
            chapter_nb = chapter.get('n')

                    # Section

            for section in chapter.findall('.//div[@type="section"]'):
                section_nb = section.get('n')

                            #Para

                for para in section.findall('.//p'):
                    para_nb = para.get('n')

                                    #Sentence

                    for sentence in para.findall('.//s'):
                        sentence_nb = sentence.get('n')

                                # Word. On récupère les attributs qui nous intéressent.

                        for word in sentence.findall('.//w'):
                            word_nb = word.get('n')
                            word_lemma = word.get('lemma')
                            word_token = word.text
                            word_udpos = word.get('udpos')
                            word_uppos = word.get("uppos")
                            word_prpos = word.get("prpos")

                            xpath = book_nb+'-'+chapter_nb+'-'+section_nb+'-'+para_nb+'-'+sentence_nb+'-'+word_nb

                            attr = word_lemma + "/" + word_token + "/" + word_udpos + "/" + word_uppos + "/" + word_prpos

                            attr_str = str(attr)

                            xpath_str = str(xpath)

                            liste.append(xpath_str + "\t(" + attr_str + ")")


#On écrit le fichier de sortie

with open(path_out, 'w', encoding="utf8") as out:
    out.write("Inventaire de formes :" + "\n" + "\n" + '\n'.join(liste))
```
+97 −0
Original line number Diff line number Diff line
%% Cell type:code id:29f21c1a tags:

``` python
#Script Python qui transforme la première lettre des lemmes en minuscule, qui capitalise les lemmes des noms propres, et délie les lettres ligaturées.
```

%% Cell type:code id:e0ecdc95 tags:

``` python
#On renseigne les chemins des fichiers

path_in = ""
path_out = ""
```

%% Cell type:code id:376eeb6e tags:

``` python
import xml.etree.ElementTree as ET
import re

    # On ouvre le fichier d'entrée

with open(path_in, encoding="utf8") as xml:

    # On importe le XML-TEI d'entrée et on le lit.
    tree = ET.parse(path_in)
    root = tree.getroot()

        #On boucle sur les balises w en reprenant la hiérarchie

        # Book

    for book in root.findall('.//div[@type="book"]'):
        book_nb = book.get('n')

                # Chapter

        for chapter in book.findall('.//div[@type="chapter"]'):
            chapter_nb = chapter.get('n')

                    # Section

            for section in chapter.findall('.//div[@type="section"]'):
                section_nb = section.get('n')

                            #Para

                for para in section.findall('.//p'):
                    para_nb = para.get('n')

                                    #Sentence

                    for sentence in para.findall('.//s'):
                        sentence_nb = sentence.get('n')

                                # Word. On récupère les attributs qui nous intéressent

                        for word in sentence.findall('.//w'):
                            word_nb = word.get('n')
                            word_lemma = word.get('lemma')
                            word_token = word.text
                            word_udpos = word.get('udpos')
                            word_uppos = word.get("uppos")
                            word_prpos = word.get("prpos")

                                # On transforme les lemmes en minuscules :

                            lemma_min = word_lemma.lower()
                            word.set('lemma', lemma_min)
                            word_lemma2 = word.get('lemma')

                                # On capitalise les lemmes des noms propres :

                            if word_udpos == "PROPN":

                                lemma_cap = word_lemma2.capitalize()
                                word.set('lemma', lemma_cap)

                            word_lemma3 = word.get('lemma')

                                # On délie les lettres liées

                            lemma_lig = word_lemma3.replace('œ', 'oe')
                            word.set('lemma', lemma_lig)

                            word_lemma4 = word.get('lemma')

                            lemma_lig2 = word_lemma4.replace('æ', 'ae')
                            word.set('lemma', lemma_lig2)



#On écrit le fichier de sortie

tree.write(path_out, xml_declaration=False, encoding="unicode")
```
+267 −0
Original line number Diff line number Diff line
%% Cell type:markdown id:11a737a9 tags:

#Script Python qui récupère les attributs des tokens dans un XML et les dispose dans un tableur, pour vérification des erreurs concernant subj/expl et (i)obj en relation avec leurs verbes, en se fondant sur le score de dépendance.

%% Cell type:code id:879b8e0a tags:

``` python
import xml.etree.ElementTree as ET
import re
import csv
```

%% Cell type:code id:40c33ae3 tags:

``` python
#On renseigne les chemins des fichiers

path_in = ""
path_out = ""
path_out_2 = ""
path_out_3 = ""
```

%% Cell type:code id:64a7b859 tags:

``` python
def get_w_text(word):

    """
    Function taking a <tei:w> element and
    returning its compiled textual content.

    :param word: ET.Element('w')

    """

    # Preparing the return string as an empty string.
    texte = ""

    # If there is text directly inside <w> element and
    # before the first child, add it.
    if word.text:
        texte += str(word.text)

    # Loop on all current <w> children.
    for item in word:

        # If current child is <tei:height> or <tei:supplied>
        if item.tag == 'height' or item.tag == 'supplied':
            # Add text.
            texte += str(item.text)
            # If any, add the text following current child.
            if item.tail:
                texte += str(item.tail)

        # If current child is <tei:lb>, add the following text.
        elif item.tag == 'lb':
            if item.tail:
                texte += str(item.tail)

        # If current child is <tei:choice>, add the second child of <choice>
        # (<tei:reg> or <tei:expan>), then add the text following current child if any.
        elif item.tag == 'choice':
            texte += str(item[1].text)
            if item.tail:
                texte += str(item.tail)

        # If current child is <tei:c>, add its text, then the following text if any.
        elif item.tag == 'c':
            texte += item.text
            if item.tail:
                texte += str(item.tail)


        # If current child is <tei:hi>, add its text, then the following text if any.
        elif item.tag == 'hi':
            texte += item.text
            if item.tail:
                texte += item.tail

        # If current child is <tei:add>, loop on its children and do the same checks.
        elif item.tag == 'add':
            # On refait tous les tests.
            if item.find('.') == None :
                texte = str(item.text)

            else:

                if item.text:
                    texte += str(item.text)

                for subitem in item:
                    if subitem.tag == 'lb':
                        if subitem.tail:
                            texte += str(subitem.tail)
                    elif subitem.tag == 'choice':
                        texte += str(subitem[1].text)
                        if subitem.tail:
                            texte += str(subitem.tail)
        else:
            print(f"Please modify me, I can't deal with this token yet:\n\t{ET.tostring(word).decode('utf-8')}")

    return texte
```

%% Cell type:code id:f08992c2 tags:

``` python
#On part des NP-subj/obj/iobj pour chercher le verbe

futurcsv = []
nosubj_liste = []
manysubj_liste = []

    # On ouvre le fichier d'entrée

with open(path_in, encoding="utf8") as xml:

    # On importe le XML-TEI d'entrée et on le lit.

    tree = ET.parse(path_in)
    root = tree.getroot()

        #On boucle sur les balises w en reprenant la hiérarchie

        # Book

    for book in root.findall('.//div[@type="book"]'):
        book_nb = book.get('n')

                # Chapter

        for chapter in book.findall('.//div[@type="chapter"]'):
            chapter_nb = chapter.get('n')

                    # Section

            for section in chapter.findall('.//div[@type="section"]'):
                section_nb = section.get('n')

                            #Para

                for para in section.findall('.//p'):
                    para_nb = para.get('n')

                    #Sentence

                    for sentence in para.findall('.//s'):
                        sentence_nb = sentence.get('n')

                        sentence_tokens = {}
                        verbe_recteur = {}
                        recteur = False

                        # Word. On crée une liste "sentence_tokens" avec le texte et les attributs de l'élément w, et le chemin

                        for count, word in enumerate(sentence.findall('.//w'), 1):

                            path = str(book_nb)+'-'+str(chapter_nb)+'-'+str(section_nb)+'-'+str(para_nb)+'-'+str(sentence_nb)+"-"+str(count)

                            sentence_tokens[path]=[word.text, word.attrib]

                            # On vérifie si le w est un verbe, et on enregistre son chemin

                            if word.get("prpos") == "Vvc":
                                recteur = True
                                verbe_recteur[path] = [word.text, word.attrib, 0]

                        if recteur == True:

                            for path in sentence_tokens.keys():

                                #On récupère les attributs/texte de w en relation avec path

                                word_function = sentence_tokens[path][1]["function"]
                                word_prpos = sentence_tokens[path][1]["prpos"]
                                word_nb = sentence_tokens[path][1]['n']
                                word_lemma = sentence_tokens[path][1]['lemma']
                                word_token = sentence_tokens[path][0]
                                word_head = sentence_tokens[path][1]["head"]

                                #Liste des fonctions dépendantes du verbe à vérifier, et formatage des informations

                                fonctionverif = ["nsubj", "expl", "iobj", "obj"]

                                if word_function in fonctionverif:

                                    try:

                                        vpath = "-".join(path.split("-")[:-1])+"-"+word_head
                                        corvb = verbe_recteur[vpath]

                                        if word_function == "nsubj":
                                            verbe_recteur[vpath][2] += 1

                                        futurcsv.append({
                                            "Phrase":"-".join(path.split("-")[:-1]),
                                            "Fonction":word_function,
                                            "Num":word_nb,
                                            "Token":word_token,
                                            "Verbe":sentence_tokens[vpath][0],
                                            "VerbeNb":word_head,
                                            "DistAbsoluNP-V":abs(int(word_nb)-int(word_head))

                                        })

                                    except:

                                        vpath = "-".join(path.split("-")[:-1])+"-"+word_head
                                        corvb = sentence_tokens[vpath]

                                        futurcsv.append({
                                            "Phrase":"-".join(path.split("-")[:-1]),
                                            "Fonction":word_function,
                                            "Num":word_nb,
                                            "Token":word_token,
                                            "Verbe": f"Is not a verb but {corvb[1]['prpos']} : {corvb[0]}",
                                            "VerbeNb":word_head,
                                            "DistAbsoluNP-V":abs(int(word_nb)-int(word_head))
                                        })

                            for vpath in verbe_recteur.keys():
                                if verbe_recteur[vpath][2] == 0:
                                    #print(f"Le verbe suivant n'a pas de sujet :" + vpath)

                                    #nosubj = f"Le verbe suivant (" + str(sentence_tokens[vpath][0]) +") n'a pas de sujet :" + vpath

                                    nosubj = str(sentence_tokens[vpath][0]) + "," + vpath

                                    nosubj_liste.append(nosubj)

                                elif verbe_recteur[vpath][2] > 1:

                                    manysubj = str(sentence_tokens[vpath][0]) + "," + str(verbe_recteur[vpath][2]) + "," + vpath

                                    manysubj_liste.append(manysubj)

                        else:
                            futurcsv.append({
                                "Phrase":"-".join(path.split("-")[:-1]),
                                "Fonction":"",
                                "Num":"",
                                "Token":"",
                                "Verbe":"No Vvc",
                                "VerbeNb":"",
                                "DistAbsoluNP-V":""

                            })

#On écrit les fichiers de sortie

with open(path_out, 'w', encoding="utf8", newline="") as out:
    fieldnames = list(futurcsv[0].keys())
    writer = csv.DictWriter(out, fieldnames=fieldnames)

    writer.writeheader()

    for item in futurcsv:

        writer.writerow(item)

with open(path_out_2, 'w', encoding="utf8") as out_2:
     out_2.write("Liste de verbes sans sujet lié au verbe dans la même phrase :" + "\n" + "\n" + "Verbe,Xpath" + "\n" + "\n" + '\n'.join(nosubj_liste))

with open(path_out_3, 'w', encoding="utf8") as out_3:
    out_3.write("Liste de verbes avec plusieurs sujets dans la même phrase :" + "\n" + "\n" + "Verbe,Nb_Subjet,XPath" + "\n" + "\n" + '\n'.join(manysubj_liste))
```