定义传递一串文本的get_triples_dict()
函数
作为参数。该函数首先将参数字符串转换为
小写,然后返回一个包含所有键的字典
独特的连续三个字母字符来自文本,以及
对应的值是连续三次的次数
字母字符出现在文本中。使用isalpha()
方法
检查一个字符是否是字母。字典应该只
包含多次出现的条目。你的字典后
已创建并填充,您需要删除任何键值对
具有相应的值1
。
我需要帮助编写此get_triples_dict
函数:
def get_triples_dict(text):
def test_get_triples_dict():
print("1.")
print_dict_in_key_order(get_triples_dict('super, duper'))
print("\n2.")
print_dict_in_key_order(get_triples_dict("ABC ABC ABC"))
print("\n3.")
print_dict_in_key_order(get_triples_dict("Sometimes the smallest things make more room in your heart"))
print("\n4.")
print_dict_in_key_order(get_triples_dict("My favourite painting is the painting i did of my dog in that painting in my den"))
答案 0 :(得分:0)
我不打算为你完成任务,但下面是你需要做的好开始。我相信你可以编写对单词进行排序并打印出字典的代码。确保学习每一行,然后在得到一般想法后,编写自己的版本。
def get_triples_dict(text):
d = dict()
text = text.lower().replace(' ', '') # set to lowercase and remove spaces
for i in range(len(text) - 2): # stops early to prevent index out of bounds exception
bit = text[i: i + 3] # characters in groups of 3
if all(c.isalpha() for c in bit): # all characters must be alphabetic
if not bit in d: # if there's no entry
d[bit] = 0
d[bit] += 1
copy = d.copy() # we cannot remove items from a list we are looping over (concurrent modification exception)
for key, value in copy.items():
if value == 1: # remove items with counts of 1
d.pop(key)
return d