我想使用.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))
Answers:
您必须使用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's translate method.
print(s.translate(translator))
这应该输出:
string with punctuation inside of it Does this work I hope so
string.punctuation不包括引号。我们将如何调整此代码以按键string.punctuation以及用户指定的字符进行裁剪?或语句?
string.punctuation包括双引号(双引号和单引号)-即使在我的示例中,它也去除了双引号。如果您想自定义哪些内容除了剥离str.punctuation,正好连接string.punctuation你也想去掉,就像一串字符translator = str.maketrans({key: None for key in string.punctuation + 'abc'}),如果你想删除标点和文字的任何事件a,b或c。
str.maketrans('', '', string.punctuation)也可以。无论如何,都不需要循环,甚至str.maketrans(dict.fromkeys(string.punctuation))在这里会更好。
str.translate的调用签名已更改,并且显然删除了参数deletechars。你可以用
import re
fline = re.sub('['+string.punctuation+']', '', fline)
而是创建一个表,如其他答案所示。
在python3.x中,可以使用:
import string
#make translator object
translator=str.maketrans('','',string.punctuation)
string_name=string_name.translate(translator)
我只是比较了三种方法的速度。translate比re.sub预编译慢10倍左右。并且str.replace比re.sub大约快3倍。通过str.replace我的意思是:
for ch in string.punctuation:
s = s.replace(ch, "'")