似乎应该有一种比以下更简单的方法:
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)
有?
当前回答
我通常用这样的词:
>>> s = "string. With. Punctuation?" # Sample string
>>> import string
>>> for c in string.punctuation:
... s= s.replace(c,"")
...
>>> s
'string With Punctuation'
其他回答
这可能不是最好的解决方案,但我就是这样做的。
import string
f = lambda x: ''.join([i for i in x if i not in string.punctuation])
这是我写的一个函数。它不是很有效,但很简单,您可以添加或删除任何您想要的标点符号:
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
您也可以这样做:
import string
' '.join(word.strip(string.punctuation) for word in 'text'.split())
对于严肃的自然语言处理(NLP),您应该让像SpaCy这样的库通过标记化处理标点符号,然后您可以根据需要手动调整。
例如,您希望如何处理单词中的连字符?例外情况,如缩写?开始和结束引号?URL?在NLP中,将“let’s”这样的收缩分隔为“let”和“s”以进行进一步处理通常很有用。
这里有一个使用RegEx的简单方法
import re
punct = re.compile(r'(\w+)')
sentence = 'This ! is : a # sample $ sentence.' # Text with punctuation
tokenized = [m.group() for m in punct.finditer(sentence)]
sentence = ' '.join(tokenized)
print(sentence)
'This is a sample sentence'