web-dev-qa-db-fra.com

supprimer la ponctuation avec regex - python

Je dois utiliser regex pour supprimer la ponctuation au début et fin d'un mot. Il semble que regex serait la meilleure option pour cela. Je ne veux pas que la ponctuation soit supprimée de mots comme «tu», c'est pourquoi je n'utilise pas .replace (). Merci d'avance =)

15
user2696287

Vous n'avez pas besoin d'expression régulière pour effectuer cette tâche. Utilisez str.strip avec string.punctuation :

>>> import string
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> '!Hello.'.strip(string.punctuation)
'Hello'

>>> ' '.join(Word.strip(string.punctuation) for Word in "Hello, world. I'm a boy, you're a girl.".split())
"Hello world I'm a boy you're a girl"
39
falsetru

Je pense que cette fonction sera utile et concise pour supprimer la ponctuation:

import re
def remove_punct(text):
    new_words = []
    for Word in text:
        w = re.sub(r'[^\w\s]','',Word) #remove everything except words and space#how 
                                        #to remove underscore as well
        w = re.sub(r'\_','',w)
        new_words.append(w)
    return new_words
0
Shalini Baranwal

Vous pouvez supprimer la ponctuation d'un fichier texte ou d'un fichier de chaîne particulier en utilisant une expression régulière comme suit: 

new_data=[]
with open('/home/rahul/align.txt','r') as f:
    f1 = f.read()
    f2 = f1.split()



    all_words = f2 
    punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' 
    # You can add and remove punctuations as per your choice 
    #removing stop words in hungarian text and  english text and 
    #display the unpunctuated string
    # To remove from a string, replace new_data with new_str 
    # new_str = "My name$#@ is . rahul -~"

    for Word in all_words: 
        if Word not in punctuations:
           new_data.append(Word)

    print (new_data)

P.S. - Identifiez-vous correctement selon les besoins. J'espère que cela vous aidera!

0
rahul ranjan