2014-12-02 87 views
2

我有這段代碼。這個想法是從一個字符串中獲得最常出現的模態動詞。例如,如果'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新手。任何幫助將不勝感激。

回答

2

當您實例化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' 
+0

喜!感謝您的答覆。我怎樣才能讓它返回只是'可能'作爲一個字或字符串。 – user3078335 2014-12-02 20:14:00

+0

@ user3078335查看我的編輯,你可以直接編制索引'[0]'獲得'most_common'中的第一項,然後''0]'獲得該元組的第一個元素。 – CoryKramer 2014-12-02 20:16:22

+0

非常感謝!還有一件事,'.split'是做什麼的? – user3078335 2014-12-02 20:20:43

1

而不是過濾的話,過濾計數:

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 
0

我是不是欺騙?

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