[InternLM 实战营笔记 - 作业] 02 - python 基础 | InternLM 实战营笔记

30 阅读1分钟

1 单词计数

1.1 题目

请用Python实现一个wordcount函数,统计英文字符串中每个单词出现的次数。返回一个字典,key为单词,value为对应单词出现的次数。

1.2 代码

from collections import defaultdict
import re

def word_count(text):
    text = re.sub(r"[^\w\s]", "", text)
    text = text.lower()
    text_list = text.split()
    cnt = defaultdict(int)

    for word in text_list:
        cnt[word] += 1
    return cnt


if __name__ == "__main__":
    text = """Hello world!  
This is an example.  
Word count is fun.  
Is it fun to count words?  
Yes, it is fun!"""
    word_cnt = word_count(text)
    print(word_cnt)

屏幕截图 2024-08-04 222306.png

debug 记录

创建 ssh 连接已在前文中记录:[InternLM 实战营笔记 - 基础工具] 01 - InternStudio 和环境 | InternLM 实战营笔记 - 掘金 (juejin.cn)

屏幕截图 2024-08-04 222838.png