首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从字符串中获取三元组字符

从字符串中获取三元组字符
EN

Stack Overflow用户
提问于 2018-05-19 13:26:02
回答 1查看 676关注 0票数 0

定义get_triples_dict()函数,该函数将一个文本字符串作为参数传递。该函数首先将参数字符串转换为小写,然后返回一个字典,字典中的键都是文本中唯一的连续三个字母字符,相应的值是这三个连续字母字符在文本中出现的次数。使用isalpha()方法检查字符是否为字母。字典应该只包含出现多次的条目。在创建并填充字典之后,您需要删除具有相应值1的所有键-值对。

我需要帮助来编写这个get_triples_dict函数:

代码语言:javascript
复制
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"))

EN

回答 1

Stack Overflow用户

发布于 2018-05-19 14:56:08

我不会为你完成你的作业,但下面是你需要做的一个很好的开始。我相信您可以编写代码对单词进行排序并打印出字典。一定要仔细研究每一行,一旦你有了大致的想法,就写出你自己的版本。

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50422077

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档