如何在python中计算字符串中的字符时忽略标点符号

2024-09-28 03:13:51 发布

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

在我的家庭作业中,有一个问题是写一个长度为_(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行代码。在

很抱歉,我不能正确地编辑我的代码,这是我第一次在这里提出问题,有很多我需要学习,但请帮助我这个问题。谢谢。在


Tags: of字符串代码stringreturnaslinethis
3条回答

您可以使用string.punctuation删除标点符号。在

>>> from string import punctuation
>>> text = "text,. has ;:some punctuation."
>>> text = ''.join(ch for ch in text if ch not in punctuation)
>>> text # with no punctuation
'text has some punctuation'

使用字符串.strip(s[,字符]) https://docs.python.org/2/library/string.html

在函数中,将x替换为strip(x,['.',',',',':',';','!', '?']在

如果需要,可添加更多标点符号

首先,您需要创建一个没有您想要忽略的字符的新字符串(看一下string library,尤其是{}),然后split()将得到的字符串(句子)分成子字符串(单词)。除此之外,我建议使用type annotation,而不是像这样的注释。在

def words_of_length(n: int, s: str) -> list:
    return [x for x in ''.join(char for char in s if char not in __import__('string').punctuation).split() if len(x) == n]

>>> words_of_length(3, 'Guido? van, rossum. is the best!'))
['van', 'the']

或者,您可以用您想忽略的字符定义一个变量,而不是string.punctuation。在

相关问题 更多 >

    热门问题