InternStudio關卡(Python)

塵埃飛揚發表於2024-07-11

任務一:wordcount函式

請實現一個wordcount函式,統計英文字串中每個單詞出現的次數。返回一個字典,key為單詞,value為對應單詞出現的次數。
在開發機中建立python_task1.py檔案,輸入以下內容,並且執行python python_task1.py

# 請實現一個wordcount函式,統計英文字串中每個單詞出現的次數。返回一個字典,key為單詞,value為對應單詞出現的次數。
import string


def wordcount(s):
    # 去掉標點符號
    s = s.translate(str.maketrans('', '', string.punctuation))
    
    # 將字串轉換為小寫
    s = s.lower()
    
    # 使用split()方法將字串分割成單詞列表
    words = s.split()
    
    # 建立一個空字典來儲存單詞及其出現次數
    word_count = {}
    
    # 遍歷單詞列表
    for word in words:
        # 如果單詞已經在字典中,則增加其計數
        if word in word_count:
            word_count[word] += 1
        # 如果單詞不在字典中,則將其新增到字典並設定計數為1
        else:
            word_count[word] = 1
    
    # 返回單詞計數字典
    return word_count

# 測試示例
text = """
Got this panda plush toy for my daughter's birthday,
who loves it and takes it everywhere. It's soft and
super cute, and its face has a friendly look. It's
a bit small for what I paid though. I think there
might be other options that are bigger for the
same price. It arrived a day earlier than expected,
so I got to play with it myself before I gave it
to her.
"""
result = wordcount(text)
print(result)

執行結果為:

{'got': 2, 'this': 1, 'panda': 1, 'plush': 1, 'toy': 1, 'for': 3, 'my': 1, 'daughters': 1, 'birthday': 1, 'who': 1, 'loves': 1, 'it': 5, 'and': 3, 'takes': 1, 'everywhere': 1, 'its': 3, 'soft': 1, 'super': 1, 'cute': 1, 'face': 1, 'has': 1, 'a': 3, 'friendly': 1, 'look': 1, 'bit': 1, 'small': 1, 'what': 1, 'i': 4, 'paid': 1, 'though': 1, 'think': 1, 'there': 1, 'might': 1, 'be': 1, 'other': 1, 'options': 1, 'that': 1, 'are': 1, 'bigger': 1, 'the': 1, 'same': 1, 'price': 1, 'arrived': 1, 'day': 1, 'earlier': 1, 'than': 1, 'expected': 1, 'so': 1, 'to': 2, 'play': 1, 'with': 1, 'myself': 1, 'before': 1, 'gave': 1, 'her': 1}

任務二:在開發機上debug wordcount函式

連結遠端開發機,並且安裝對應的debug外掛

執行debug設定

進入wordcount函式

在除錯的過程觀察變數的變化

相關文章