我试图创建一个程序,从一个给定的输入句子中删除所有类型的标点符号。代码看起来有点像这样
from string import punctuation
sent = str(input())
def rempunc(string):
for i in string:
word =''
list = [0]
if i in punctuation:
x = string.index(i)
word += string[list[-1]:x]+' '
list.append(x)
list_2 = word.split(' ')
return list_2
print(rempunc(sent))然而,输出结果如下:
This state ment has @ 1 ! punc.
['This', 'state', 'ment', 'has', '@', '1', '!', 'punc', '']为什么标点符号不被完全移除?我是不是在密码里遗漏了什么?
我试着在第7行中用x-1修改x,但是没有帮助。现在我被困住了,不知道还能尝试什么。
发布于 2022-04-02 20:07:44
重复的字符串切片在这里是不必要的。
我建议使用filter()筛选出每个单词的不想要的字符,然后将结果读入列表理解。在那里,您可以使用第二个filter()操作来删除空字符串:
from string import punctuation
def remove_punctuation(s):
cleaned_words = [''.join(filter(lambda x: x not in punctuation, word))
for word in s.split()]
return list(filter(lambda x: x != "", cleaned_words))
print(remove_punctuation(input()))这一产出如下:
['This', 'state', 'ment', 'has', '1', 'punc']https://stackoverflow.com/questions/71720767
复制相似问题