Python 从除撇号外的 unicode 字符串中删除标点符号

标签 python regex unicode punctuation

我找到了几个主题,并找到了这个解决方案:

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/

相关文章:

c# - 获取网页中所有 url 的列表

javascript - 正则表达式仅匹配第一次出现的情况

swift - PURE Swift 中的十六进制字符串到字符

python - 使用Python拆分数据 block 时出错

python - 如何从 python 调用 vala 构造函数? (使用 GObject 自省(introspection))

python - 无法重新采样然后绘制 Pandas 数据框

python - 工业强度csv阅读器(python)

python - 如何在 Pygame 中使闪屏图像在屏幕上停留 5 秒?

regex - 在 Google 工作表中使用 REGEXMATCH 过滤以过滤掉单元格中包含的文本

python - 在 python 上使用 Selenium Webdriver 发送 unicode