任务一:  Python实现一个wordcount函数

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

在开发机中创建一个python_taks1.py 文件,填写内容如下:

import socket
import re
def wordcount(text):
    # 使用字典来存储单词及其出现的次数
    word_counts = {}
    # 使用正则表达式来分割单词,忽略标点符号
    import re
    words = re.findall(r'\b\w+\b', text.lower())  # 转换为小写以统一计数
    
    # 遍历单词列表并更新字典中的计数
    for word in words:
        if word in word_counts:
            word_counts[word] += 1
        else:
            word_counts[word] = 1
            
    # 返回包含单词计数的字典
    return word_counts

# 获取主机名
def get_hostname():
    hostname = socket.gethostname()
    match = re.search(r'-(\d+)$', hostname)
    name = match.group(1)
    
    return name

# 使用示例
text = f"""☁️ Welcome {get_hostname()} user, welcome to the ShuSheng LLM Practical Camp Course!
        😀 Let’s go on a journey through ShuSheng Island together.
    """
print(wordcount(text))

返回结果:

{'welcome': 2, '40068764': 1, 'user': 1, 'to': 1, 'the': 1, 'shusheng': 2, 'llm': 1, 'practical': 1, 'camp': 1, 'course': 1, 'let': 1, 's': 1, 'go': 1, 'on': 1, 'a': 1, 'journey': 1, 'through': 1, 'island': 1, 'together': 1}

任务二:在开发机上debug wordcount函数

debug命令为下面这种形式:

进行debug调试时使用了Debug扩展,关于命令的解释如下:

  • /usr/bin/env: 这是一个环境变量,用于在系统上查找Python解释器的路径。

  • /root/.conda/bin/python: 这是Python解释器的路径,看起来像是在用户的家目录下的Conda环境中。

  • /root/.vscode-server/extensions/ms-python.debugpy-2024.6.0-linux-x64/bundled/libs/debugpy/adapter/../../debugpy/launcher: 这是debugpy调试器的启动脚本的路径。它位于Visual Studio Code的扩展目录中。

  • 47197: 这通常是调试器监听的端口号。

  • --: 在命令行参数解析中,--后面跟着的是传递给脚本的参数。

  • /root/demo/python_task1.py: 这是要调试的Python脚本的路径。

当运行debug以后,我的显示如下:

因为wordcount 使用了re进行了处理,words列表中都是从text字符串中取出来的词。

我在这里打了断点,我们可以单步执行以下看一下字典word_counts的变化:

当单步执行完一次循环以后我们可以看到,字典中存入了一对键值对,当我们再一次单步执行一边循环,会增加一对新的键值对。