gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:21:29 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com