编写按块加载数据的生成器(3)
做得好!您刚刚创建了一个可用于处理大型文件的生成器函数。
现在,让我们像之前那样,用您的生成器函数来处理世界银行数据集。您将逐行处理文件,统计数据集中某一列中各个国家出现的次数,并将其存入字典。不过,这次不只处理 1000 行数据,而是要处理整个数据集!
生成器函数 read_large_file() 和 CSV 文件 'world_dev_ind.csv' 已预加载,随时可用。开始吧!
本练习是课程的一部分
Python 工具箱
练习说明
- 在上下文管理器中使用
open(),将文件 'worlddevind.csv' 绑定为file。 - 完成
for循环,使其迭代调用read_large_file()所返回的生成器,从而处理文件的所有行。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Initialize an empty dictionary: counts_dict
counts_dict = {}
# Open a connection to the file
with ____ as ____:
# Iterate over the generator from read_large_file()
for line in ____:
row = line.split(',')
first_col = row[0]
if first_col in counts_dict.keys():
counts_dict[first_col] += 1
else:
counts_dict[first_col] = 1
# Print
print(counts_dict)