在我的家庭作业中,有一个问题是写一个长度为_(N,s)的虚词,它可以从一个字符串中选择具有一定长度的唯一单词,但忽略标点符号。在
我想做的是:
def words_of_length(N, s): #N as integer, s as string
#this line i should remove punctuation inside the string but i don't know how to do it
return [x for x in s if len(x) == N] #this line should return a list of unique words with certain length.
所以我的问题是我不知道如何删除标点符号,我确实查看了“从字符串中删除标点的最佳方法”和相关问题,但这些在我的级别上看起来太难了,而且因为我的老师要求它应该包含不超过2行代码。在
很抱歉,我不能正确地编辑我的代码,这是我第一次在这里提出问题,有很多我需要学习,但请帮助我这个问题。谢谢。在
您可以使用
string.punctuation
删除标点符号。在使用字符串.strip(s[,字符]) https://docs.python.org/2/library/string.html
在函数中,将x替换为strip(x,['.',',',',':',';','!', '?']在
如果需要,可添加更多标点符号
首先,您需要创建一个没有您想要忽略的字符的新字符串(看一下string library,尤其是{}),然后
split()
将得到的字符串(句子)分成子字符串(单词)。除此之外,我建议使用type annotation,而不是像这样的注释。在或者,您可以用您想忽略的字符定义一个变量,而不是
string.punctuation
。在相关问题 更多 >
编程相关推荐