我有一个从字符串列表中删除标点符号的函数:
def strip_punctuation(input):
x = 0
for word in input:
input[x] = re.sub(r'[^A-Za-z0-9 ]', "", input[x])
x += 1
return input
我最近修改了我的脚本以使用 Unicode 字符串,以便我可以处理其他非西方字符。此函数在遇到这些特殊字符时中断,只返回空的 Unicode 字符串。如何可靠地从 Unicode 格式的字符串中删除标点符号?
unicode.translate()
方法:
import unicodedata
import sys
tbl = dict.fromkeys(i for i in xrange(sys.maxunicode)
if unicodedata.category(unichr(i)).startswith('P'))
def remove_punctuation(text):
return text.translate(tbl)
您还可以使用正则表达式模块支持的r'p{P}'
:
import regex as re
def remove_punctuation(text):
return re.sub(ur"p{P}+", "", text)
在Python 3中使用J.F. Sebastian的解决方案:
import unicodedata
import sys
tbl = dict.fromkeys(i for i in range(sys.maxunicode)
if unicodedata.category(chr(i)).startswith('P'))
def remove_punctuation(text):
return text.translate(tbl)
unicodedata
模块的category
函数循环访问字符串,以确定字符是否为标点符号。
有关category
的可能输出,请参阅 unicode.org 关于一般类别值的文档
import unicodedata.category as cat
def strip_punctuation(word):
return "".join(char for char in word if cat(char).startswith('P'))
filtered = [strip_punctuation(word) for word in input]
<小时 />此外,请确保正确处理编码和类型。本演示文稿是一个很好的起点。
基于丹尼斯答案的较短版本
import unicodedata
def strip_punctuation(text):
"""
>>> strip_punctuation(u'something')
u'something'
>>> strip_punctuation(u'something.,:else really')
u'somethingelse really'
"""
punctutation_cats = set(['Pc', 'Pd', 'Ps', 'Pe', 'Pi', 'Pf', 'Po'])
return ''.join(x for x in text
if unicodedata.category(x) not in punctutation_cats)
input_data = [u'somehting', u'something, else', u'nothing.']
without_punctuation = map(strip_punctuation, input_data)