我想使用.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))
wkl.. 158
您必须使用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
这很好.令人遗憾的是,此主题的Google排名结果已弃用,速度较慢或难以遵循. (5认同)
小智.. 22
在python3.x中,可以使用以下命令完成:
import string #make translator object translator=str.maketrans('','',string.punctuation) string_name=string_name.translate(translator)
elzell.. 21
str.translate的调用签名已更改,显然已删除参数deletechars.你可以用
import re fline = re.sub('['+string.punctuation+']', '', fline)
相反,或创建一个表,如另一个答案所示.
您必须使用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
在python3.x中,可以使用以下命令完成:
import string #make translator object translator=str.maketrans('','',string.punctuation) string_name=string_name.translate(translator)
str.translate的调用签名已更改,显然已删除参数deletechars.你可以用
import re fline = re.sub('['+string.punctuation+']', '', fline)
相反,或创建一个表,如另一个答案所示.