繁体   English   中英

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

[英]how to ignore punctuation when counting characters in string in python

在我的作业中有一个问题是关于编写一个函数 words_of_length(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.  

所以我的问题是我不知道如何删除标点符号,我确实查看了“从字符串中删除标点符号的最佳方法”和相关问题,但这些在我的 lvl 中看起来太难了,而且因为我的老师要求它不应包含更多超过 2 行代码。

抱歉,我无法正确编辑有问题的代码,这是我第一次在这里提问,我需要学习很多东西,但是请帮助我解决这个问题。 谢谢。

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

在你的函数中用 strip (x, ['.', ',', ':', ';', '!', '?']

如果需要,添加更多标点

首先,您需要创建一个没有要忽略的字符的新字符串(查看字符串库,特别是string.punctuation ),然后split()结果字符串(句子) 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您可以定义一个变量,其中包含您想自己忽略的字符。

您可以使用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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM