我找到了几个主题,并找到了这个解决方案:
sentence=re.sub(ur"[^\P{P}'|-]+",'',sentence)
这应该删除除 ' 之外的所有标点符号,问题是它还删除了句子中的所有其他内容。
例子:
>>> sentence="warhol's art used many types of media, including hand drawing, painting, printmaking, photography, silk screening, sculpture, film, and music."
>>> sentence=re.sub(ur"[^\P{P}']+",'',sentence)
>>> print sentence
'
当然我要的是保持句子没有标点符号,“warhol's”保持原样
期望的输出:
"warhol's art used many types of media including hand drawing painting printmaking photography silk screening sculpture film and music"
"austro-hungarian empire"
编辑: 我也试过使用
tbl = dict.fromkeys(i for i in xrange(sys.maxunicode)
if unicodedata.category(unichr(i)).startswith('P'))
sentence = sentence.translate(tbl)
但这会去除所有标点符号
最佳答案
指定您不想删除的所有元素,即\w
、\d
、\s
等。这就是 ^
运算符在方括号中的含义。 (匹配任何除外)
>>> import re
>>> sentence="warhol's art used many types of media, including hand drawing, painting, printmaking, photography, silk screening, sculpture, film, and music."
>>> print re.sub(ur"[^\w\d'\s]+",'',sentence)
warhol's art used many types of media including hand drawing painting printmaking photography silk screening sculpture film and music
>>>
关于Python 从除撇号外的 unicode 字符串中删除标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29930287/