python - 尝试找出句子中出现次数最多的情态动词

标签 python list dictionary

我有这个代码。这个想法是从字符串中获取最常出现的情态动词。例如,如果“can”出现两次,且多于其余次数,则该函数应返回“can”,或者如果不存在情态动词,则返回“none”。

def check_modals(s):
    modals = ['can', 'could', 'may', 'might', 'must', 'will', "should", "would"]
    from collections import Counter
    Counter([modal for modals, modal in s])
    counts = Counter(modals)
    c = counts.most_common(1)

    return{c}

仍然是一个Python新手。任何帮助将不胜感激。

最佳答案

当您实例化 Counter 时,我将使用列表理解来过滤仅包含 modals 列表中存在的单词。除此之外,你的想法是正确的。

def check_modals(s):
        modals = ['can', 'could', 'may', 'might', 'must', 'will', 'should', 'would']
        from collections import Counter
        counts = Counter([word for word in s if word in modals])
        if counts:
            return counts.most_common(1)[0][0]
        else:
            return ''

>>> s = 'This is a test sentence that may or may not have verbs'
>>> check_modals(s.split())
'may'

关于python - 尝试找出句子中出现次数最多的情态动词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27257965/

相关文章:

python - Django 管理命令不显示我的库的日志

python - 从/使用函数参数作为键和默认值作为值创建字典

arrays - 将数组元素附加到字符串(Swift)

python - 计算由空格分隔的未指定数量的整数并使用字典查找 python 中每个数字的出现次数

python - 关于我制作的小型转换器的IF语句问题

python - 试图制作数学游戏,但数学不起作用

python - tkinter 通过 VNC 无需物理显示

r - 按名称将列表子集化为组,并将这些组保留为列表,以便原始列表将是 R 中的列表列表

c# - C# 中的多维数组列表或列表?

java - 从通用 "Object"列表创建自定义对象列表会导致 ClassCastException