开始使用免费开始使用

综合应用(2)

做得很好!您已经实现了遍历某一列并构建字典的功能,其中键是语言名称,值是该语言的推文数量。

在本练习中,您将把上一个练习中开发的功能封装成一个函数,在函数内部返回生成的字典,并用合适的参数来调用该函数。

为方便起见,pandas 包已按 pd 导入,且 'tweets.csv' 文件已读取到变量 tweets_df 中。

本练习是课程的一部分

Python 函数入门

查看课程

练习说明

  • 定义函数 count_entries(),它有两个参数。第 1 个参数 df 表示 DataFrame,第 2 个参数 col_name 表示列名。
  • 补全 for 循环中 if-else 语句体:若键已在字典 langs_count 中,则在其当前值上加 1;否则将该键加入 langs_count 并将其值设为 1。在代码中使用循环变量 entry
  • count_entries() 函数中返回字典 langs_count
  • 调用 count_entries() 函数,并传入 tweets_df 和列名 'lang'。将函数调用的结果赋给变量 result

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Define count_entries()
def ____(____, ____):
    """Return a dictionary with counts of 
    occurrences as value for each key."""

    # Initialize an empty dictionary: langs_count
    langs_count = {}
    
    # Extract column from DataFrame: col
    col = df[col_name]
    
    # Iterate over lang column in DataFrame
    for entry in col:

        # If the language is in langs_count, add 1
        if entry in langs_count.keys():
            ____
        # Else add the language to langs_count, set the value to 1
        else:
            ____

    # Return the langs_count dictionary
    

# Call count_entries(): result


# Print the result
print(result)
编辑并运行代码