checkio练习题:popular-words

In this mission your task is to determine the popularity of certain words in the text.

At the input of your function are given 2 arguments: the text and the array of words the popularity of which you need to determine.

When solving this task pay attention to the following points:

The words should be sought in all registers. This means that if you need to find a word "one" then words like "one", "One", "oNe", "ONE" etc. will do.
The search words are always indicated in the lowercase.
If the word wasn’t found even once, it has to be returned in the dictionary with 0 (zero) value.
Input: The text and the search words array.

Output: The dictionary where the search words are the keys and values are the number of times when those words are occurring in a given text.

Example:

popular_words('''
When I was One
I had just begun
When I was Two
I was nearly new
''', ['i', 'was', 'three', 'near']) == {
    'i': 4,
    'was': 3,
    'three': 0,
    'near': 0
}

Precondition:
The input text will consists of English letters in uppercase and lowercase and whitespaces.


在此任务中,您的任务是确定文本中某些单词的受欢迎程度。
在函数的输入处给出了2个参数:文本和需要确定其受欢迎程度的单词数组。
解决此任务时请注意以下几点:
应在所有登记册中寻求这些词语。这意味着如果你需要找一个单词“one”,那么像“one”,“One”,“oNe”,“ONE”等单词就可以了。
搜索词始终以小写字母表示。
如果甚至没有找到该单词,则必须在字典中返回0(零)值。

输入:文本和搜索词数组。
输出:搜索单词是键的字典,值是给定文本中出现这些单词的次数。

 

def popular_words(text: str, words: list) -> dict:
#     li = text.lower().split()
#     data = {}
#     for word in words:
#         data[word] = li.count(word)
#     return data
    return {word: text.lower().split().count(word) for word in words}

if __name__ == '__main__':
    print("Example:")
    print(popular_words('''
                        When I was One
                        I had just begun
                        When I was Two
                        I was nearly new
                        ''', ['i', 'was', 'three', 'near']))
    # These "asserts" are used for self-checking and not for an auto-testing
    assert popular_words('''
                        When I was One
                        I had just begun
                        When I was Two
                        I was nearly new
                        ''', ['i', 'was', 'three', 'near']) == {
                                'i': 4,
                                'was': 3,
                                'three': 0,
                                'near': 0
                            }
    print("Coding complete? Click 'Check' to earn cool rewards!")

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值