Python 试着找出句子中最常见的情态动词
我有这个密码。其思想是从字符串中获取出现次数最多的情态动词。例如,如果“can”出现两次,并且出现次数超过其余部分,则函数应返回“can”,如果不存在情态动词,则应返回“none”Python 试着找出句子中最常见的情态动词,python,list,dictionary,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 fo
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新手。任何帮助都将不胜感激。当您实例化您的
计数器时,我将使用列表理解来筛选仅包括模态中出现的单词。除此之外,你的想法是对的
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'
与其过滤单词,不如过滤计数:
from collections import Counter
def check_modals(s):
counts = Counter(s)
modals = ['can', 'could', 'may', 'might', 'must', 'will', "should", "would"]
for key in counts.keys():
if key not in modals:
del counts[key]
c = counts.most_common(1)
return c[0][0]
print check_modals('can can'.split(' '))
印刷品:
can
我在作弊吗
def check_modals(s, modals={'can':0, 'could':0, 'may':0, 'might':0,
'must':0, 'will':0, "should":0, "would":0}):
for w in s.split():
if w in modals: modals[w]+=1
# EDIT I will return both the most frequent and also the count number
k, v = max(modals.iteritems(), key=lambda item:item[1])
return (k, v) if v > 0 else (None, None)
从口译员那里
>>> s = '''I have this code. The idea is to get the most occurring modal verb from a string. For example, if 'can' appears twice, and more than the rest, the function should return 'can', and 'none' if no modal verb present.'''
>>> check_modal(s)
('should', 1)
>>>
你好谢谢你的回复。我怎样才能让它以单词或字符串的形式返回“may”。@user3078335查看我的编辑,您只需索引[0]
即可获取最常见的中的第一项,然后再次[0]
即可获取该元组的第一个元素。非常感谢!还有一件事,“.split”做什么?@user3078335是str
类的方法,它根据指定的分隔符将字符串解析为字符串列表。因为我没有指定分隔符,所以它在空白处拆分,并生成一个单词列表。好的。这是有道理的。再次感谢。