本问题已经有最佳答案,请猛点这里访问。
所以我有一个单词列表,我想删除所有标点符号。 这是我的代码
def removePunctuation(words):
return set([s.translate(None, string.punctuation) for s in words])
wordsStripped = removePunctuation(words)
我收到以下错误
TypeError: translate() takes exactly one argument (2 given)
我已经尝试了几种不同的方法来做到这一点,但没有运气,肯定有一种更简单的方法来做到这一点?
我是python的新手,请原谅我,如果这是一个糟糕的问题,任何帮助将不胜感激。
我建议您阅读translate()的文档:docs.python.org/3/library/stdtypes.html#str.translate
您可能希望首先使用str.maketrans构建转换表。请参阅:stackoverflow.com/questions/41535571/
我认为他是从stackoverflow.com/questions/265960/得到的,这似乎是一个非常受尊敬的答案。
我认为你的混淆源于使用python 3的python 2语法
测试了@Chris_Rands声明,我确信他是对的。 @OP的示例是为python 2编写的,但是他有python-3.x标记。
在我看来,欺骗中接受的答案是使用OP中使用的完全相同的translate()形式,这是来自Python 2. OP在这里提出的错误表明他们正在使用Python 3.这个签名功能发生了变化。对于当前的问题,这种欺骗似乎不太有用。
在Python 3中制作所需转换表以删除ASCII标点符号的最佳方法是执行table = str.maketrans('', '', string.punctuation),如链接重复目标问题页面中的krinker答案所示。
import string
trans_table = str.maketrans("","", string.punctuation
def removePunctuation(words):
return set([s.translate(trans_table) for s in words])
wordsStripped = removePunctuation(words)
string.maketrans在Python 3.1中已弃用,并在更新版本中删除。 您应该使用str.maketrans。 在我看来,3参数版本是最可读的:str.maketrans('', '', string.punctuation)
看看@PatrickHaugh说的话,这对我来说很有意义。 The string.maketrans() function is deprecated and is replaced by new static methods, bytes.maketrans() and bytearray.maketrans(). This change solves the confusion around which types were supported by the string module. Now, str, bytes, and bytearray each have their own maketrans and translate methods with intermediate translation tables of the appropriate type.在docs.python.org/3/whatsnew/3.1.html上找到
在此示例中,maketrans()是不必要的。 您可以直接使用dict comp。
请注意,None可用于代替trans_table中的""。
你也可以这样做:
words_stripped = ''.join(c for c in s if not c in string.punctuation)
免责声明:下面的代码在IPython shell中使用Python 2语法 - 在Python 3中似乎已经改变了string.translate函数 - 您的上述解决方案适用于Python 2。
解决@Chris_Rands在此答案评论中提到的时间安排:
In [17]: %timeit s.translate(None, string.punctuation)
100000 loops, best of 3: 15.6 μs per loop
In [18]: %timeit ''.join(c for c in s if not c in string.punctuation)
1000 loops, best of 3: 1.04 ms per loop
In [19]: %timeit ''.join(c for c in s if not c in punctuation_set)
1000 loops, best of 3: 632 μs per loop
这是通过将s设置为此处生成的5个段落来完成的:https://www.lipsum.com/feed/html
所以,是的,翻译方法是迄今为止最快的。 同时......根据您需要执行此操作的次数,您并不需要担心这一点。
使用您能想到的最简单的方法,然后使用分析工具(CProfiler)来确定如果您的脚本不够快,您的瓶颈究竟在哪里。
你可以这样做,它将在python 3中工作,但它会比使用str.translate()慢,即使这是通过使punctuation一组优化