使用string.punctuation python时出错

时间:2015-08-02 17:26:50

标签: python string python-3.x punctuation

我尝试在python中使用string.punctuation函数。我在python 3.5版本中使用它。这是我的以下代码:

import string
def check(text):
    x=set(text.punctuation())

我收到以下错误

'str' object has no attribute 'punctuation'

请使用正确的方法帮助我。我甚至尝试过使用ispunct()函数。

我尝试解决这个问题,如下面的链接所示,但无法理解。

Best way to strip punctuation from a string in Python

1 个答案:

答案 0 :(得分:3)

punctuationstring模块的方法,而不是字符串对象属性。

>>> import string
>>> 
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

如果您想从文本中获取punctuation,可以在set中使用生成器表达式:

set(i for i in text if i in string.punctuation)