我有一个函数,从字符串列表中删除标点符号:
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
Run Code Online (Sandbox Code Playgroud)
我最近修改了我的脚本以使用Unicode字符串,所以我可以处理其他非西方字符.当遇到这些特殊字符并且只返回空的Unicode字符串时,此函数会中断.如何从Unicode格式的字符串中可靠地删除标点符号?
jfs*_*jfs 73
你可以使用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)
Run Code Online (Sandbox Code Playgroud)
你也可以使用regex模块r'\p{P}'
支持的:
import regex as re
def remove_punctuation(text):
return re.sub(ur"\p{P}+", "", text)
Run Code Online (Sandbox Code Playgroud)
met*_*mit 19
如果你想在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)
Run Code Online (Sandbox Code Playgroud)
您可以使用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]
Run Code Online (Sandbox Code Playgroud)
此外,请确保您正确处理编码和类型.这个演示文稿是一个很好的起点: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)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
24947 次 |
最近记录: |