我有这个代码。这个想法是要从字符串中获取最常出现的情态动词。例如,如果“ 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'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句