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

新手上路,请多包涵

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

 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 格式的字符串中删除标点符号?

原文由 acpigeon 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 563
2 个回答

您可以使用 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)

原文由 jfs 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果你想在 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)

原文由 metakermit 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题