有没有办法删除字符串中每个单词开头和结尾的标点符号而不是中间的标点符号? Python

Is there a way to remove punctuation at the start and end of each word in string but not the middle? Python

写一个函数beautify_sentence(句子,标点符号)returns一个新句子(字符串类型)从单词中删除所有指定的标点符号(单词用白色分隔space).

例如,句子“?hello !mango! and, ban,ana yum apple!”带有标点符号“?!,”的结果将返回一个字符串 "hello mango and ban,ana yum apple"。

注意 "ban,ana" 仍然包含逗号。

这是开始的好地方。将逗号留在香蕉中会有点棘手。将来,我建议发布您对代码的尝试,即使您认为它很粗糙。以这种方式引导您朝着正确的方向前进要容易得多。祝你好运!

import string

def beautify_sentence(sentence, punctuation):
        beautiful = sentence.translate(str.maketrans('', '', string.punctuation))
        return beautiful

print(beautify_sentence('?hello !mango! and, ban,ana yum apple!',  '?!,'))

这应该可以为您完成。

from string import punctuation

a="""'?hello !mango! and, ban,ana yum apple!',  '?!,' """
new=[i.strip(punctuation) for i in a.split()]
print(" ".join(new))

输出:

hello mango and ban,ana yum apple