我有这个代码。这样做的目的是从字符串中获取最常出现的情态动词。例如,如果“ 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/

10-10 21:15