2017-10-16 60 views
-1

像一個例子:獲得最後三個字母在字典蟒蛇

text = ' "west best worst first tapping snapping in a pest the straining 
singing forest living' 
a_dict = get_last_three_letters_dict(text) 
remove_less_than_2(a_dict) 
print("1.") 
print_dict_in_key_order(a_dict)  

text = 'Kublai Khan does not necessarily believe everything Marco Polo says 
when he describes the cities visited on his expeditions but the emperor of 
the Tartars does continue listening to the young Venetian with greater 
attention and curiosity than he shows any other messenger or explorer of his' 
a_dict = get_last_three_letters_dict(text) 
remove_less_than_2(a_dict) 
print("2.") 
print_dict_in_key_order(a_dict) 

我試圖將字符串成小寫轉換,然後返回,其具有的任何單詞的最後三個字母鍵的字典對象在長度大於2的文本串中,以及相應的值,即以這些最後三個字母結尾的文本參數串中的單詞數。

測試代碼刪除結果字典中的最後三個字母只出現在文本字符串中的任何對,我嘗試了下面的函數,但它不起作用。

def get_last_three_letters_dict(sentence): 
     sentence = dict(sentence) 
     tails = [] 
     for letter in sentence: 
      if len(name) > 2: 
       tails.append(name[-3:].lower()) 
     return (''.join(tails) + ":") 

預期:

1. 
est : 4 
ing : 5 
rst : 2 

2. 
han : 2 
his : 2 
ing : 2 
oes : 2 
the : 4 
+0

你會期望'dict(句子)'做什麼?對句子調用字典毫無意義。 – abccd

回答

1

這裏有一個解決方案,它收集句子中所有長度超過2個字母的單詞的最後三個字母,然後返回多次出現的單詞。

from collections import Counter 

def get_letter_dict(sentence): 
    sentence = sentence.lower().split() 
    c = Counter(word[-3:] for word in sentence if len(word) > 2) 
    return dict((a,b) for a,b in c.items() if b > 1) 
1

由於下面的函數返回一個字典,鍵值對將返回回報是隨機的順序。但它做你想要的。

(注意到,當我編輯它刪除鍵值對值爲1,我犯了一個錯誤,修正它,現在它應該工作,你想要的方式它的工作)

def get_last_three_letters_dict(sentence): 
    #Split the sentence into a list of words 
    words = sentence.split() 

    #Create an empty list to store tails in 
    tails = [] 

    #Create list of last three letters of all words with length greater than 2 
    for word in words: 
     if len(word) > 2: 
      tails.append(word[-3:].lower()) 

    #create empty dictionary for word tails + tail frequencies 
    tail_dict = dict() 

    for tail in tails: 
    #Add a key if tail is not already in dictionary. Set its value to 1. 
     if tail not in tail_dict.keys(): 
      tail_dict[tail] = 1 

    #If the tail is already a key, add 1 to its value 
     else: 
      tail_dict[tail] = tail_dict[tail] + 1 

    #Delete key-value pairs with value 1 
    for key in list(tail_dict.keys()): 
     if tail_dict[key] == 1:    
      del tail_dict[key] 
    return tail_dict