繁体   English   中英

从Unicode格式的字符串中删除标点符号

[英]Remove punctuation from Unicode formatted strings

我有一个从字符串列表中删除标点符号的函数:

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)

您还可以使用regex模块支持的r'\\p{P}'

import regex as re

def remove_punctuation(text):
    return re.sub(ur"\p{P}+", "", text)

如果要在Python 3中使用JF 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上有关常规Category值的文档

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]

此外,请确保正确处理编码和类型。 此演示文稿是一个不错的起点: http : //bit.ly/unipain

根据Daenyth答案的简短版本

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)

暂无
暂无

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

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