Удаление пунктуации из списка python

Я знаю, что существует множество примеров удаления знаков препинания, но я хочу знать, как это сделать наиболее эффективно. У меня есть список слов, которые я прочитал из текстового файла и разделил

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

Как быстрее всего проверить каждое слово и убрать все знаки препинания? Я могу сделать это с кучей кода, но я знаю, что это не самый простой способ.

Спасибо!!


person English Grad    schedule 07.06.2012    source источник
comment
Можете ли вы предоставить образец ввода и вывода (или указать, что составляет ваш набор знаков препинания)?   -  person Levon    schedule 07.06.2012
comment
конечно, нет проблем. Текстовый файл представляет собой стихотворение. первые две строчки гласят: Тайгер! Тайгер! горящие ярко В лесах ночных, Я хотел бы, чтобы они заканчивались в списке без запятых или восклицательных знаков. Набор знаков препинания, который мне нужно удалить, -,!?. Спасибо!   -  person English Grad    schedule 07.06.2012
comment
выглядит как дубликат этого stackoverflow.com/questions/265960/   -  person Joran Beasley    schedule 07.06.2012
comment
@JoranBeasley: я не думаю, что это обман. Мой ответ подходит к этому вопросу, но не к другому.   -  person Sven Marnach    schedule 07.06.2012


Ответы (4)


Я думаю, что самый простой способ - извлечь только слова, состоящие из букв:

import re

with open("Tyger.txt") as f:
    words = re.findall("\w+", f.read())
person Sven Marnach    schedule 07.06.2012
comment
как это будет работать со специальными символами, которые не являются знаками препинания? - person luke14free; 07.06.2012
comment
Это отлично работает, спасибо. Я очень ценю помощь. Я так многому учусь у всех вас, ребята - person English Grad; 07.06.2012
comment
@EnglishGrad: обратите внимание на использование Свеном ключевого слова with для открытия входного файла. Использование блока with предпочтительнее использования f = open()... close() и намного предпочтительнее использования stuff = open().read().... В последнем примере вы теряете возможность явного close() файла после чтения/записи. - person Joel Cornett; 07.06.2012
comment
@ luke14free: указав флаги re.LOCALE или re.UNICODE и установив языковой стандарт, вы можете заставить это работать по желанию. Для стандартных строк без каких-либо флагов он будет соответствовать только набору [a-zA-Z0-9_]. Дополнительную информацию см. в документации. - person Sven Marnach; 07.06.2012

Я бы пошел с чем-то вроде этого:

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

Он удалит только то, что действительно необходимо, и не создаст чрезмерную перегрузку из-за переназначения.

person luke14free    schedule 07.06.2012

Например:

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)

or

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

Второй гораздо быстрее.

person georg    schedule 07.06.2012
comment
Обратите внимание, что ваши два решения делают разные вещи. "fearful,symmetry" в конечном итоге станет одним словом при втором подходе. - person Sven Marnach; 07.06.2012
comment
@SvenMarnach: да, правильно. Тем не менее, translate в 4 раза быстрее, чем re. - person georg; 07.06.2012

>>> 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)

Отпечатки:

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 

Или с файлом:

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

И если вы хотите создать список строк:

>>> lines=[]
>>> with open('tyger.txt', 'r') as WmBlake:
...    lines.append(re.sub(r'["-,!?.]','',WmBlake.read()))
person the wolf    schedule 07.06.2012
comment
+1 за публикацию полного стихотворения;) Хотя теперь оно больше похоже на Буковски, чем на Блейка. - person georg; 07.06.2012