我想用re模块从文本中提取所有标点符号。我怎么能这样做?
答案 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)
#,,!