在dict python

时间:2017-10-16 04:29:13

标签: python

例如:

 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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)