HOME: Popular Words —— 计算文本中指定字符串出现的次数

CheckIO是一个通过闯关游戏学习编程的网站(Python和JavaScript)。通过解题开发新“岛屿”,同时,通过做任务获得Quest Points解锁会员题目。
文章内容:题目、我自己的思路和代码以及优秀代码,如果想看大神解题可以直接跳到“优秀代码”部分。
本题链接:https://py.checkio.org/en/mission/popular-words/

题目

在这项任务中,你要计算文本中每个要求的单词出现的次数。
给定两个参数:分别是文本和单词。

注意:

  1. 不区分大小写,如:“one”, “One”, “oNe”, "ONE"都算"one"的出现
  2. 要搜索的单词一般以小写形式给出
  3. 如果单词没有出现过,次数为0
  4. 文本中包含大写字母、小写字母和空格

输入: 文本和以列表形式给出的单词
输出: 以字典形式给出,其中各单词为字典的键,其出现的次数为对应的值

举个栗子

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
}

难度: Elementary+

题目框架

def popular_words(text: str, words: list) -> dict:
    # your code here
    return None

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!")

思路

No.1

  1. text 进行分割;
  2. 创建字典,将 words 里的单词出现次数设为 0
  3. 遍历 text,如果该单词在 count 里,对应的次数 +1

No.2

  1. text 进行分割;
  2. 创建 count 列表,添加 words 里的单词在 text 中出现次数;
  3. 使用 zip() 函数,将 wordscount 列表中的元素一一对应,形成元组,使用 dict() 函数,将 zip() 函数生成的元组转化为字典。

代码

No.1

def popular_words(text: str, words: list) -> dict:
    # your code here
    count = {}
    text = text.lower().split()
    for i in words:
         count[i] = 0
    for i in text:
        if i in count:
            count[i] += 1
    return count

No.2 zip() 函数

def popular_words(text: str, words: list) -> dict:
    # your code here
    text = text.lower().split()
    count = [text.count(i) for i in words]
    return dict(zip(words, count))

优秀代码

No.1

def popular_words(text, words):
    lower_count = text.lower().split().count
    return {word: lower_count(word) for word in words}

原来可以这样,感觉像定义了一个函数,学到了
感觉和直接写到 return 里差不多?

No.2

def popular_words(text, words):
    return dict(zip(words, map(text.lower().split().count, words)))

用了 map() 函数计算对应单词的出现次数

知识点

.split() 函数在不写参数时,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值