Tokenizer - Module python d'analyse syntaxique et de grammaire, tokenization

Overview

Tokenizer

Le Tokenizer est un analyseur lexicale, il permet, comme Flex and Yacc par exemple, de tokenizer du code, c'est à dire transformer du code en liste tokens. En l'occurence, contrairement à Flex and Yacc, la liste de token sera hiérarchisée et les tokens sont typés.

Qu'est-ce que c'est quoi dis donc un token ?

Un token, litteralement, c'est un jeton... Bof bof comme définition... Repprenons. Un token c'est une chaîne de caractères qui, ensemble, ont une signification. La chaîne de caractères qui forme un jeton est appelée Lexeme.

Et à quoi ça sert ?

La tokenization, c'est la prmière étape de la compilation ou de l'interprétation de la plupart des langages informatiques. Prenons Python par exemple, l'ordinateur ne sait absolument pas quoi faire avec le ficher qu'on lui donne, il le découpe donc pour avoir chacun des mots du code et pouvoir comprendre ce qu'on lui demande.


Exemple :

Du code python comme celui ci :

def hello(name) :
    print("Hello", name, "!")

sera convertit en YAML (ou n'importe quel autre langage de stockage de données comme JSON par exemple)

---
- {value: 'def', type: function.declaration}
- {value: 'hello', type: name.funciton.declaration}
- {value: '(', type: punctuation.begin}
- {value: 'name', type: parameter}
- {value: ')', type: punctuation.end}
- {value: ':', type: start.node}
- - {value: 'print', type: function}
  - {value: '(', type: punctuation.begin}
  - {value: '"Hello"', type: string}
  - {value: ',', type: separator}
  - {value: 'name', type: variable}
  - {value: ',', type: separator}
  - {value: '"!"', type: string}
  - {value: ')', type: punctuation.end}

Ici les tokens sont hiérarchisés et typés, c'est à dire que pour chaque nœud, une nouvelle liste est créée et pour chaque token, un attribut de type lui est appliqué.

Le typage des tokens peut être utile car le tokenizateur peut, avec une grammaire, faire un fichier de coloration syntaxique si l'on indique dans le type la couleur du token.


Spécifications

technologie outil
Langage Python
Version du langage 3.10
Gestionnaire des packets PIP
Gestionnaire d'environnement VirtualEnvironment
Environnement Windows 7/10
Librairie PyYaml, re

Installation

pip install -e git+https://github.com/Manolo-dev/tokenizer.git#egg=tokenizer


To do list

  • Grammaire
  • Classe Token
  • Classe Node
  • Main
  • Gestion des erreurs
  • Lecteur Yaml

Grammaire

Oui, il faut une grammaire à l'outil de grammaire ! Grammaception !

Corps

Le corps se compose d'au moins deux parties, variables, qui contient des expressions regexp, et les modules, dont main, seul module obligatoire.

  • variables

  • main

Module

main est le seul module qui est appelé sans qu'on l'incluse manuellement.

Les modules traitent le code et s'occupe de la grosse part du travail, ils peuvent utiliser les variables définies dans le module, dans un module encore ouvert (variables locale) ou dans variables.

Méthodes

  • include, inclut un module.

  • match, corresptond à un SI token correspond FAIRE, assigne à l'objet courant le token trouvé et éxécute le module donné (nommé ou non).

  • save, assigne un type à l'objet courant et enregistre le token dans la liste des tokens.

  • if, vérifie la condition donnée (liste de trois arguments, le premier l'opérateur, le second et le troisième les valeurs à tester). Exemple: if: ['==', ;a, ;b]

  • begin, crée un nœud et le débute.

  • end, ferme le nœud.

  • ignore, ne fait pas avancer le texte.

  • var, modifie les variables de la même manière que le module variables, la variable _ représente le token trouvé.

  • error, génère une erreur (équivalent au raise python)

  • print, affiche le texte donné dans la console.

Variables

Il y deux moyens d'utiliser les variables. Dans le cas d'une variable d'exemple appelée var, on peut faire :

  • ;var, seul dans l'élément.

  • {{var}}, peut-être placé n'importe où dans l'élément.

  • str:n, permet de supprimer n caractères à la chaîne str.

Exemple

variables:
  open: '\('
  close: '\)'
main:
  - match: ;open
    save: 'open'
    begin: # Ceci est un module non nommé
    - match: ;close
      save: 'close'
      end: 1
    - include: 'main'
  - match: '[^()]+' # pour éviter de prendre des parenthèses involontairement
    save: 'other'
  - match: ;close
    error: il y a une parenthèse de fermeture en trop

Cette grammaire fait de la parenthétisation simple, en simple, ça transforme ceci :

1 / (3 * (1 + 2))

en :

---
- {value: '1 / ', type: 'other'}
- {value: '(', type: 'open'}
- - {value: '3 * ', type: 'other'}
  - {value: '(', type: 'open'}
  - - {value: '1 + 2', type: 'other'}
  - {value: ')', type: 'close'}
- {value: ')', type: 'close'}
Owner
Manolo
Hi ! My name is Manolo, I am 18 years old. I have been programming since I was 11 or 12 (I can't quite remember) with BASIC CASIO. And i love code !
Manolo
A full spaCy pipeline and models for scientific/biomedical documents.

This repository contains custom pipes and models related to using spaCy for scientific documents. In particular, there is a custom tokenizer that adds

AI2 1.3k Jan 03, 2023
Trankit is a Light-Weight Transformer-based Python Toolkit for Multilingual Natural Language Processing

Trankit: A Light-Weight Transformer-based Python Toolkit for Multilingual Natural Language Processing Trankit is a light-weight Transformer-based Pyth

652 Jan 06, 2023
Random Directed Acyclic Graph Generator

DAG_Generator Random Directed Acyclic Graph Generator verison1.0 简介 工作流通常由DAG(有向无环图)来定义,其中每个计算任务$T_i$由一个顶点(node,task,vertex)表示。同时,任务之间的每个数据或控制依赖性由一条加权

Livion 17 Dec 27, 2022
Local cross-platform machine translation GUI, based on CTranslate2

DesktopTranslator Local cross-platform machine translation GUI, based on CTranslate2 Download Windows Installer You can either download a ready-made W

Yasmin Moslem 29 Jan 05, 2023
Behavioral Testing of Clinical NLP Models

Behavioral Testing of Clinical NLP Models This repository contains code for testing the behavior of clinical prediction models based on patient letter

Betty van Aken 2 Sep 20, 2022
Python implementation of TextRank for phrase extraction and summarization of text documents

PyTextRank PyTextRank is a Python implementation of TextRank as a spaCy pipeline extension, used to: extract the top-ranked phrases from text document

derwen.ai 1.9k Jan 06, 2023
Code for paper "Role-oriented Network Embedding Based on Adversarial Learning between Higher-order and Local Features"

Role-oriented Network Embedding Based on Adversarial Learning between Higher-order and Local Features Train python main.py --dataset brazil-flights C

wang zhang 0 Jun 28, 2022
Simple Annotated implementation of GPT-NeoX in PyTorch

Simple Annotated implementation of GPT-NeoX in PyTorch This is a simpler implementation of GPT-NeoX in PyTorch. We have taken out several optimization

labml.ai 101 Dec 03, 2022
Practical Natural Language Processing Tools for Humans is build on the top of Senna Natural Language Processing (NLP)

Practical Natural Language Processing Tools for Humans is build on the top of Senna Natural Language Processing (NLP) predictions: part-of-speech (POS) tags, chunking (CHK), name entity recognition (

jawahar 20 Apr 30, 2022
Using context-free grammar formalism to parse English sentences to determine their structure to help computer to better understand the meaning of the sentence.

Sentance Parser Executing the Program Make sure Python 3.6+ is installed. Install requirements $ pip install requirements.txt Run the program:

Vaibhaw 12 Sep 28, 2022
Python powered crossword generator with database with 20k+ polish words

crossword_generator Generate simple crossword puzzle from words and definitions fetched from krzyżowki.edu.pl endpoints -/ string:word - returns js

0 Jan 04, 2022
CDLA: A Chinese document layout analysis (CDLA) dataset

CDLA: A Chinese document layout analysis (CDLA) dataset 介绍 CDLA是一个中文文档版面分析数据集,面向中文文献类(论文)场景。包含以下10个label: 正文 标题 图片 图片标题 表格 表格标题 页眉 页脚 注释 公式 Text Title

buptlihang 84 Dec 28, 2022
Study German declensions (dER nettE Mann, ein nettER Mann, mit dEM nettEN Mann, ohne dEN nettEN Mann ...) Generate as many exercises as you want using the incredible power of SPACY!

Study German declensions (dER nettE Mann, ein nettER Mann, mit dEM nettEN Mann, ohne dEN nettEN Mann ...) Generate as many exercises as you want using the incredible power of SPACY!

Hans Alemão 4 Jul 20, 2022
Sorce code and datasets for "K-BERT: Enabling Language Representation with Knowledge Graph",

K-BERT Sorce code and datasets for "K-BERT: Enabling Language Representation with Knowledge Graph", which is implemented based on the UER framework. R

Weijie Liu 834 Jan 09, 2023
Code for our paper "Mask-Align: Self-Supervised Neural Word Alignment" in ACL 2021

Mask-Align: Self-Supervised Neural Word Alignment This is the implementation of our work Mask-Align: Self-Supervised Neural Word Alignment. @inproceed

THUNLP-MT 46 Dec 15, 2022
NLP - Machine learning

Flipkart-product-reviews NLP - Machine learning About Product reviews is an essential part of an online store like Flipkart’s branding and marketing.

Harshith VH 1 Oct 29, 2021
Simple Python script to scrape youtube channles of "Parity Technologies and Web3 Foundation" and translate them to well-known braille language or any language

Simple Python script to scrape youtube channles of "Parity Technologies and Web3 Foundation" and translate them to well-known braille language or any

Little Endian 1 Apr 28, 2022
Yet another Python binding for fastText

pyfasttext Warning! pyfasttext is no longer maintained: use the official Python binding from the fastText repository: https://github.com/facebookresea

Vincent Rasneur 230 Nov 16, 2022