2024-05-16 23:22:53 发布
网友
我想用Python中的一个字符串中的“”替换所有标点字符。
有什么有效的下列味道吗?
text = text.translate(string.maketrans("",""), string.punctuation)
有一个更健壮的解决方案依赖于regex排除,而不是通过大量标点字符列表包含。
import re print(re.sub('[^\w\s]', '', 'This is, fortunately. A Test! string')) #Output - 'This is fortunately A Test string'
regex捕获不是字母数字或空白字符的任何内容
这个答案是针对Python 2的,只适用于ASCII字符串:
string模块包含两个可以帮助您的东西:标点符号列表和“maketrans”函数。下面是如何使用它们的:
import string replace_punctuation = string.maketrans(string.punctuation, ' '*len(string.punctuation)) text = text.translate(replace_punctuation)
来自Best way to strip punctuation from a string in Python的改性溶液
import string import re regex = re.compile('[%s]' % re.escape(string.punctuation)) out = regex.sub(' ', "This is, fortunately. A Test! string") # out = 'This is fortunately A Test string'
有一个更健壮的解决方案依赖于regex排除,而不是通过大量标点字符列表包含。
regex捕获不是字母数字或空白字符的任何内容
这个答案是针对Python 2的,只适用于ASCII字符串:
string模块包含两个可以帮助您的东西:标点符号列表和“maketrans”函数。下面是如何使用它们的:
来自Best way to strip punctuation from a string in Python的改性溶液
相关问题 更多 >
编程相关推荐