繁体   English   中英

从Unicode字符串中去除特殊字符和标点符号

[英]Strip special characters and punctuation from a unicode string

我正在尝试从可能包含非ASCII字母的Unicode字符串中删除标点符号。 我尝试使用regex模块:

import regex
text = u"<Üäik>"
regex.sub(ur"\p{P}+", "", text)

但是,我注意到字符<>不会被删除。 有谁知道为什么,还有其他方法可以从Unicode字符串中删除标点符号吗?

编辑:我尝试过的另一种方法是:

import string
text = text.encode("utf8").translate(None, string.punctuation).decode("utf8")

但我想避免将文本从unicode转换为字符串和向后转换。

<>归为数学符号(Sm)而不是标点符号(P)。 您可以匹配:

regex.sub('[\p{P}\p{Sm}]+', '', text)

unicode.translate()方法也存在,并且使用字典将整数(代码点)映射到其他整数代码点,unicode字符或None None将删除该代码点。 使用ord() string.punctuation到代码点:

text.translate(dict.fromkeys(ord(c) for c in string.punctuation))

这样只会删除有限数量的ASCII标点符号。

演示:

>>> import regex
>>> text = u"<Üäik>"
>>> print regex.sub('[\p{P}\p{Sm}]+', '', text)
Üäik
>>> import string
>>> print text.translate(dict.fromkeys(ord(c) for c in string.punctuation))
Üäik

如果string.punctuation还不够,那么可以通过从0到sys.maxunicode迭代,为所有PSm代码点生成完整的str.translate()映射,然后针对unicodedata.category()测试这些值:

>>> import sys, unicodedata
>>> toremove = dict.fromkeys(i for i in range(0, sys.maxunicode + 1) if unicodedata.category(chr(i)).startswith(('P', 'Sm')))
>>> print text.translate(toremove)
Üäik

(对于Python 3,更换unicodestr ,并print ...print(...))

尝试string模块

import string,re
text = u"<Üäik>"
out = re.sub('[%s]' % re.escape(string.punctuation), '', text)
print out
print type(out)

Prints-

Üäik
<type 'unicode'>

\\p{P}匹配标点符号。

这些标点符号是

! ' # S % & ' ( ) * + , - . / : ; < = > ? @ [ / ] ^ _ { | } ~

<>不是标点符号。 因此它们不会被删除。

试试这个

re.sub('[\p{L}<>]+',"",text)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM