似乎应该有一种比以下更简单的方法:
import string
s = "string. With. Punctuation?" # Sample string
out = s.translate(string.maketrans("",""), string.punctuation)
有?
似乎应该有一种比以下更简单的方法:
import string
s = "string. With. Punctuation?" # Sample string
out = s.translate(string.maketrans("",""), string.punctuation)
有?
当前回答
您也可以这样做:
import string
' '.join(word.strip(string.punctuation) for word in 'text'.split())
其他回答
这里有一个没有正则表达式的解决方案。
import string
input_text = "!where??and!!or$$then:)"
punctuation_replacer = string.maketrans(string.punctuation, ' '*len(string.punctuation))
print ' '.join(input_text.translate(punctuation_replacer).split()).strip()
Output>> where and or then
用空格替换标点用单个空格替换单词之间的多个空格删除尾随空格(如果有)条带()
为什么你们都不用这个?
''.join(filter(str.isalnum, s))
太慢了?
这是我写的一个函数。它不是很有效,但很简单,您可以添加或删除任何您想要的标点符号:
def stripPunc(wordList):
"""Strips punctuation from list of words"""
puncList = [".",";",":","!","?","/","\\",",","#","@","$","&",")","(","\""]
for punc in puncList:
for word in wordList:
wordList=[word.replace(punc,'') for word in wordList]
return wordList
我通常用这样的词:
>>> s = "string. With. Punctuation?" # Sample string
>>> import string
>>> for c in string.punctuation:
... s= s.replace(c,"")
...
>>> s
'string With Punctuation'
对于严肃的自然语言处理(NLP),您应该让像SpaCy这样的库通过标记化处理标点符号,然后您可以根据需要手动调整。
例如,您希望如何处理单词中的连字符?例外情况,如缩写?开始和结束引号?URL?在NLP中,将“let’s”这样的收缩分隔为“let”和“s”以进行进一步处理通常很有用。