Best way to strip punctuation from a string

前端 未结 26 1913
日久生厌
日久生厌 2020-11-21 05:39

It seems like there should be a simpler way than:

import string
s = \"string. With. Punctuation?\" # Sample string 
out = s.translate(string.maketrans(\"\",\         


        
26条回答
  •  面向向阳花
    2020-11-21 06:01

    Here's one other easy way to do it using 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'
    
    

提交回复
热议问题