如何使用带有python的Re Module来提取所有标点符号?

时间:2016-02-11 11:15:14

标签: python punctuation

我想用re模块从文本中提取所有标点符号。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

>>> text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()"
>>> from string import punctuation
>>> for p in punctuation:
...     if p in text:
...             print p
...

它将打印文本中的所有标点字符。

!
#
$
%
&
(
)
*
@
^

OR

>>> text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()"
>>> [char for char in punctuation if char in text]
['!', '#', '$', '%', '&', '(', ')', '*', '@', '^']

答案 1 :(得分:0)

我不知道如何使用re模块,但您可以使用list-comprehension:

from string import punctuation
old_string = "This, by the way, has some punctuation!"
new_string = "".join(char for char in old_string if char in punctuation)
print(new_string)
#,,!