InternLM第三期实战-Python基础

InternLM第三期实战-Python基础

关卡任务-Python实现wordcount

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

"""Hello world!  
This is an example.  
Word count is fun.  
Is it fun to count words?  
Yes, it is fun!"""

实现代码:

点击查看代码
import string  
  
def wordcount(text):  
    # 移除文本中的标点符号,并转换为小写  
    # 使用str.translate来移除所有标点符号  
    # string.punctuation包含了所有的ASCII标点符号  
    translator = str.maketrans('', '', string.punctuation)  
    text_no_punctuation = text.translate(translator)  
      
    # 按空格分割文本成单词列表  
    words = text_no_punctuation.split()  
      
    # 使用字典来统计每个单词出现的次数  
    word_count = {}  
    for word in words:  
        if word in word_count:  
            word_count[word] += 1  
        else:  
            word_count[word] = 1  
      
    return word_count  
  
# 示例输入  
input_text = """Hello world!    
This is an example.    
Word count is fun.    
Is it fun to count words?    
Yes, it is fun!"""  
  
# 调用函数并打印结果  
result = wordcount(input_text)  
print(result)

最终输出结果:
image

任务2-Vscode连接InternStudio debug

首先远程连接开发机,并安装python debugger扩展。
image
在代码执行语句中打上断点,通过左侧查看即时变量值,上方有步进等调试方式。

posted @ 2024-07-15 17:44  柠檬戚风  阅读(9)  评论(0)    收藏  举报