2012-06-07 3 views
0

Je sais qu'il existe des tonnes d'exemples sur la suppression de la ponctuation, mais je veux connaître le moyen le plus efficace de le faire. J'ai une liste de mots que je lis à partir d'un fichier txt et SplitSuppression de la ponctuation d'une liste python

wordlist = open('Tyger.txt', 'r').read().split() 

Quel est le meilleur moyen de vérifier chaque mot et supprimer toute ponctuation? Je peux le faire avec un tas de code mais je sais que ce n'est pas le moyen le plus simple.

Merci!

+0

Pouvez-vous fournir un exemple d'entrée et de sortie (ou délimitez ce qui constitue votre ensemble de ponctuation)? – Levon

+0

sûr aucun problème. Le fichier texte est un poème. les deux premières lignes lisent: Tyger! Tyger! brûlant Dans les forêts de la nuit, je voudrais qu'ils se retrouvent dans la liste avec pas virgules ou des points d'exclamation. L'ensemble de puntuations dont j'ai besoin est supprimé "-,!?. Merci! –

+0

ressemble à un doublon à cela http://stackoverflow.com/questions/265960/best-way-to-strip-punctuation-from-a-string -in-python –

Répondre

2

Je pense que le plus simple est de mots d'extrait uniquement composé de lettres en premier lieu:

import re 

with open("Tyger.txt") as f: 
    words = re.findall("\w+", f.read()) 
+0

Comment serait-ce traiter avec des caractères spéciaux qui ne sont pas de ponctuation? – luke14free

+0

Cela fonctionne grand merci. –

+1

@EnglishGrad: Notez l'utilisation du mot-clé 'with' par Sven pour ouvrir le fichier d'entrée, l'utilisation d'un bloc' with' étant préférable à l'utilisation de 'f = open(). .. close() 'et _much_ préfèrent utiliser' stuff = open(). read() ... '. Dans le dernier exemple, vous perdez la possibilité de fermer explicitement'() 'le fichier après la lecture/l'écriture –

1

Par exemple:

text = """ 
Tyger! Tyger! burning bright 
In the forests of the night, 
What immortal hand or eye 
Could frame thy fearful symmetry? 
""" 
import re 
words = re.findall(r'\w+', text) 

ou

import string 
ps = string.punctuation 
words = text.translate(string.maketrans(ps, ' ' * len(ps))).split() 

Le second est beaucoup plus rapide.

+0

Notez que vos deux solutions font des choses différentes. "" craintif, la symétrie "' finira par être un seul mot avec la deuxième approche. –

+1

@SvenMarnach: oui, correct. Pourtant, traduire est 4x fois plus rapide que re. – georg

1

j'aller avec quelque chose comme ceci:

import re 
with open("Tyger.txt") as f: 
    print " ".join(re.split("[\-\,\!\?\.]", f.read()) 

Il va supprimer uniquement ce qui est vraiment nécessaire et créer une surcharge excessive habitude en raison de overmatching.

1
>>> import re 

>>> the_tyger 
'\n Tyger! Tyger! burning bright \n In the forests of the night, \n What immortal hand or eye \n Could frame thy fearful symmetry? \n \n In what distant deeps or skies \n Burnt the fire of thine eyes? \n On what wings dare he aspire? \n What the hand dare sieze the fire? \n \n And what shoulder, & what art. \n Could twist the sinews of thy heart? \n And when thy heart began to beat, \n What dread hand? & what dread feet? \n \n What the hammer? what the chain? \n In what furnace was thy brain? \n What the anvil? what dread grasp \n Dare its deadly terrors clasp? \n \n When the stars threw down their spears, \n And watered heaven with their tears, \n Did he smile his work to see? \n Did he who made the Lamb make thee? \n \n Tyger! Tyger! burning bright \n In the forests of the night, \n What immortal hand or eye \n Dare frame thy fearful symmetry? \n ' 

>>> print re.sub(r'["-,!?.]','',the_tyger) 

Prints:

Tyger Tyger burning bright 
In the forests of the night 
What immortal hand or eye 
Could frame thy fearful symmetry 

In what distant deeps or skies 
Burnt the fire of thine eyes 
On what wings dare he aspire 
What the hand dare sieze the fire 

And what shoulder what art 
Could twist the sinews of thy heart 
And when thy heart began to beat 
What dread hand what dread feet 

What the hammer what the chain 
In what furnace was thy brain 
What the anvil what dread grasp 
Dare its deadly terrors clasp 

When the stars threw down their spears 
And watered heaven with their tears 
Did he smile his work to see 
Did he who made the Lamb make thee 

Tyger Tyger burning bright 
In the forests of the night 
What immortal hand or eye 
Dare frame thy fearful symmetry 

Ou, avec un fichier:

>>> with open('tyger.txt', 'r') as WmBlake: 
... print re.sub(r'["-,!?.]','',WmBlake.read()) 

Et si vous voulez créer une liste des lignes:

>>> lines=[] 
>>> with open('tyger.txt', 'r') as WmBlake: 
... lines.append(re.sub(r'["-,!?.]','',WmBlake.read())) 
+1

+1 pour afficher le poème complet;) Bien qu'il ressemble plus à Bukowski maintenant que Blake. – georg

Questions connexes