Подтвердить что ты не робот

Как удалить знаки препинания из строки в Python 3.x с помощью .translate()?

Я хочу удалить все знаки препинания из текстового файла, используя метод .translate(). Кажется, он хорошо работает под Python 2.x, но под Python 3.4 он ничего не делает.

Мой код выглядит следующим образом, а вывод такой же, как и текст ввода.

import string
fhand = open("Hemingway.txt")
for fline in fhand:
    fline = fline.rstrip()
    print(fline.translate(string.punctuation))
4b9b3361

Ответ 1

Вам нужно создать таблицу переводов, используя maketrans, который вы передадите методу str.translate.

В Python 3.1 и новее maketrans теперь является статическим методом в типе str, поэтому вы можете использовать его для создания перевода каждого пунктуации вы хотите None.

import string

# Thanks to Martijn Pieters for this improved version

# This uses the 3-argument version of str.maketrans
# with arguments (x, y, z) where 'x' and 'y'
# must be equal-length strings and characters in 'x'
# are replaced by characters in 'y'. 'z'
# is a string (string.punctuation here)
# where each character in the string is mapped
# to None
translator = str.maketrans('', '', string.punctuation)

# This is an alternative that creates a dictionary mapping
# of every character from string.punctuation to None (this will
# also work)
#translator = str.maketrans(dict.fromkeys(string.punctuation))

s = 'string with "punctuation" inside of it! Does this work? I hope so.'

# pass the translator to the string translate method.
print(s.translate(translator))

Это должно выводить:

string with punctuation inside of it Does this work I hope so

Ответ 2

Сигнатура вызова str.translate изменилась, и, по-видимому, удаление параметров было удалено. Вы можете использовать

import re
fline = re.sub('['+string.punctuation+']', '', fline)

или создать таблицу, как показано в другом ответе.

Ответ 3

В python3.x это можно сделать, используя:

import string
#make translator object
translator=str.maketrans('','',string.punctuation)
string_name=string_name.translate(translator)

Ответ 4

Я просто сравнил три метода по скорости. translate медленнее, чем re.sub (с предварительной компиляцией) примерно в 10 раз. А str.replace быстрее, чем re.sub примерно в 3 раза. Под str.replace я имею в виду:

for ch in string.punctuation:                                                                                                     
    s = s.replace(ch, "'")