试图从字符串中删除所有标点字符,但我一直保留的所有内容//都保留在

2024-04-18 09:00:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个函数来删除字符串中的所有标点字符。我在翻译、替换、剥离等方面尝试了几种排列。我最近的尝试使用了蛮力方法:

def clean_lower(sample):
    punct = list(string.punctuation)
    for c in punct:
        sample.replace(c, ' ')
    return sample.split()

这就去掉了几乎所有的标点符号,但我在其中一个单词的前面留下了//。我似乎找不到任何方法来移除它。我甚至尝试过用sample.replace('/','')显式替换它。 我需要做什么


Tags: sample方法函数字符串cleanstringdef字符
3条回答

使用正则表达式

import re
def clean_lower(s):
    return(re.sub(r'\W','',s))

上述函数将删除除下划线以外的任何符号

使用translate是删除标点符号的最快方法,这也将删除//

import string 

s = "This is! a string, with. punctuations? //"

def clean_lower(s):
    return s.translate(str.maketrans('', '', string.punctuation))

s = clean_lower(s)
print(s)

也许你应该从你想保留什么的角度来看待它:

例如:

import string

toKeep   = set(string.ascii_letters + string.digits + " ")
toRemove = set(string.printable) - toKeep
cleanUp  = str.maketrans('', '', "".join(toRemove))

用法:

s = "Hello! world of / and dice".translate(cleanUp)

# s will be 'Hello world of  and dice'

相关问题 更多 >