logo

Python | Supprimer la ponctuation de la chaîne

Plusieurs fois, en travaillant avec Chaînes Python , nous avons un problème dans lequel nous devons supprimer certains caractères des chaînes. Cela peut avoir des applications dans le prétraitement des données dans le Python .

Exemple



  Input:   'Gfg, is best: for ! Geeks ;'   Output:   Gfg is best for Geeks    Explanation:   Here we can observe the difference between input and output we removed all the punctuation from the input and the ways to this is listed below to do that.>

Façons de supprimer la ponctuation d’une chaîne

Il existe de nombreuses façons de supprimer la ponctuation d’une chaîne, mais les principales sont répertoriées ci-dessous. Alors explorons-les un par un. Vous trouverez ci-dessous les méthodes que nous aborderons dans cet article :

lancer des lancers en java
  • Supprimer la ponctuation d'une chaîne avec Translate
  • Supprimer la ponctuation d'une chaîne avec une boucle Python
  • Supprimer la virgule d'une chaîne avec une boucle Python
  • Supprimer la ponctuation d'une chaîne avec regex
  • Utilisation d'une boucle for, d'une chaîne de ponctuation et non de l'opérateur in
  • Supprimer la ponctuation d'une chaîne avec filter()
  • Utilisation de la méthode replace()

Supprimer la ponctuation d'une chaîne avec Translate

Les deux premiers arguments en faveur chaîne.translate La méthode est constituée de chaînes vides et la troisième entrée est un Liste Python de la ponctuation qui doit être supprimée. Cela demande à la méthode Python d'éliminer la ponctuation d'une chaîne. C'est l'un des meilleures façons de supprimer la ponctuation d'une chaîne .

Python3








import> string> test_str>=> 'Gfg, is best: for ! Geeks ;'> test_str>=> test_str.translate> >(>str>.maketrans('>', '>', string.punctuation))> print>(test_str)>

>

>

Sortir:

Gfg is best for Geeks>

Supprimer la ponctuation d'une chaîne avec une boucle Python

C’est la manière brutale dont cette tâche peut être effectuée. En cela, nous vérifions les ponctuations à l'aide d'une chaîne brute contenant des ponctuations, puis nous construisons une chaîne supprimant ces ponctuations.

Python3


k algorithme de clustering



# initializing string> test_str>=> 'Gfg, is best : for ! Geeks ;'> # printing original string> print>(>'The original string is : '> +> test_str)> # initializing punctuations string> punc>=> '''!()-[]{};:'',./?@#$%^&*_~'''> # Removing punctuations in string> # Using loop + punctuation string> for> ele>in> test_str:> >if> ele>in> punc:> >test_str>=> test_str.replace(ele, '')> # printing result> print>(>'The string after punctuation filter : '> +> test_str)>

>

>

Sortir:

The original string is : Gfg, is best : for ! Geeks ; The string after punctuation filter : Gfg is best for Geeks>

Complexité temporelle : Sur)
Espace auxiliaire : O(n), où n est le nombre de caractères de la chaîne.

Supprimer la virgule d'une chaîne avec une boucle Python

C’est la manière brutale dont cette tâche peut être accomplie. En cela, nous vérifions la virgule en utilisant une chaîne brute contenant des virgules, puis nous construisons une chaîne en supprimant ces virgules.

Python3




def> remove_commas(string):> >result>=> ''> >for> char>in> string:> >if> char !>=> ','>:> >result>+>=> char> >return> result> > input_string>=> 'GFG, is, the, best.'> output_string>=> remove_commas(input_string)> print>(output_string)>

>

>

Sortir:

GFG is the best>

Supprimer la ponctuation d'une chaîne avec regex

La partie consistant à remplacer la ponctuation peut également être effectuée en utilisant expression régulière . En cela, nous remplaçons toute ponctuation par une chaîne vide en utilisant une certaine regex.

Python3




import> re> # initializing string> test_str>=> 'Gfg, is best : for ! Geeks ;'> # printing original string> print>(>'The original string is : '> +> test_str)> # Removing punctuations in string> # Using regex> res>=> re.sub(r>'[^ws]'>, '', test_str)> # printing result> print>(>'The string after punctuation filter : '> +> res)>

>

chaîne concaténer java
>

Sortir :

The original string is : Gfg, is best : for ! Geeks ; The string after punctuation filter : Gfg is best for Geeks>

Utilisation d'une boucle for, d'une chaîne de ponctuation et non de l'opérateur in

Ici, nous verrons Supprimer les ponctuations dans une chaîne à l'aide d'une boucle + chaîne de ponctuation.

Python3




# initializing string> test_str>=> 'Gfg, is best : for ! Geeks ;'> # printing original string> print>(>'The original string is : '> +> test_str)> # initializing punctuations string> punc>=> '''!()-[]{};:'',./?@#$%^&*_~'''> res>=>' '> for> ele>in> test_str:> >if> ele>not> in> punc:> >res>+>=>ele> > # printing result> print>(>'The string after punctuation filter : '> +> res)>

>

>

Sortir

The original string is : Gfg, is best : for ! Geeks ; The string after punctuation filter : Gfg is best for Geeks>

La complexité temporelle et spatiale de toutes les méthodes est la même :

tous les 2 mois

Complexité temporelle : Sur)
Espace auxiliaire : Sur)

Supprimer la ponctuation d'une chaîne avec filter()

La méthode filter() filtre les éléments d'une séquence en fonction d'une condition donnée.
Dans ce cas, nous pouvons utiliser la méthode filter() et une fonction lambda pour filtrer les caractères de ponctuation.

Python3




def> remove_punctuation(test_str):> # Using filter() and lambda function to filter out punctuation characters> >result>=> ''.join(>filter>(>lambda> x: x.isalpha()>or> x.isdigit()>or> x.isspace(), test_str))> >return> result> test_str>=> 'Gfg, is best : for ! Geeks ;'> print>(>'The original string is : '> +> test_str)> result>=> remove_punctuation(test_str)> print>(>'The string after punctuation filter : '> +> result)> #This code is contributed by Edula Vinay Kumar Reddy>

>

>

Sortir

The original string is : Gfg, is best : for ! Geeks ; The string after punctuation filter : Gfg is best for Geeks>

Complexité temporelle : Sur)
Espace auxiliaire : Sur)

Supprimer la ponctuation d'une chaîne à l'aide de la méthode replace()

Importez le module de chaîne puis initialisez la chaîne d'entrée et imprimez la chaîne d'origine. Parcourez chaque caractère de ponctuation dans la constante de ponctuation de chaîne après avoir utilisé la méthode replace() pour supprimer chaque caractère de ponctuation de la chaîne d'entrée. puis imprimez la chaîne résultante après avoir supprimé les ponctuations.

apache

Python3




import> string> # initializing string> test_str>=> 'Gfg, is best : for ! Geeks ;'> # printing original string> print>(>'The original string is : '> +> test_str)> # Removing punctuations using replace() method> for> punctuation>in> string.punctuation:> >test_str>=> test_str.replace(punctuation, '')> # printing result> print>(>'The string after punctuation filter : '> +> test_str)>

>

>

Sortir

The original string is : Gfg, is best : for ! Geeks ; The string after punctuation filter : Gfg is best for Geeks>

Analyse de complexité temporelle : O(len(string.uccion) * len(test_str)) car la boucle for parcourt tous les caractères de ponctuation de la constante string.uccion, ce qui prend un temps O(len(string.uccion)).

Analyse de l'espace auxiliaire : O(1) . Étant donné que la chaîne d'entrée est modifiée sur place, aucun espace supplémentaire n'est requis pour stocker le résultat.