python - 计算字符串中最小长度的唯一单词

标签 python function loops for-loop

我必须编写一个函数,它接受两个变量,即一个句子和一个数字。该函数应返回字符串中等于或大于该数字的唯一单词的数量。示例结果应该是:

>>> 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:

现在我不知道如何继续我的解决方案。谁能帮帮我?

最佳答案

试试这个:

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])

关于python - 计算字符串中最小长度的唯一单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16051777/

相关文章:

C - realloc 不反射(reflect)回 main

javascript - JavaScript 中检测字符串是否不是 URL?

python - 如何随机化 if/elif 语句的顺序?

r - 从一个小标题创建单独的图并将每个图单独保存在 R 中

c - 打印星形或 "X"图案

javascript - 将 Python None 转换为 JavaScript null

python - 为什么在内存缓存上调用 get() 会增加 Google App Engine 中的项目数?

python - "ModuleNotFoundError"与使用 Python 的 Azure 函数应用程序

python - 256 位整数到 256 位字符串表示

loops - 方案:如何创建一个循环将数据保存到不同名称的文件中?