我必须编写一个函数,它接受2个变量,即句子和数字。该函数应返回字符串中等于或大于该数字的唯一字数。示例结果应为:
>>> unique_func("The sky is blue and the ocean is also blue.",3)
6
我能想到的解决方案是
def unique_func(sentence,number):
sentence_split = sentence.lower().split()
for w in sentence_split:
if len(w) >= number:
现在我不知道如何继续我的解决方案。任何人都可以帮助我吗?
答案 0 :(得分:2)
试试这个:
from string import punctuation
def unique_func(sentence, number):
cnt = 0
sentence = sentence.translate(None, punctuation).lower()
for w in set(sentence.split()):
if len(w) >= number:
cnt += 1
return cnt
或者:
def unique_func(sentence, number):
sentence = sentence.translate(None, punctuation).lower()
return len([w for w in set(sentence.split()) if len(w) >= number])
答案 1 :(得分:1)
这是一个提示:
>>> set('The sky is blue and the ocean is also blue'.lower().split())
{'is', 'also', 'blue', 'and', 'the', 'sky', 'ocean'}
>>> len(set('The sky is blue and the ocean is also blue'.lower().split()))
7
答案 2 :(得分:1)
>>> from string import punctuation
>>> def unique_func(text, n):
words = (w.strip(punctuation) for w in text.lower().split())
return len(set(w for w in words if len(w) >= n))
>>> unique_func("The sky is blue and the ocean is also blue.",3)
6