如何遍历 csv 文件并用 python 字典替换其中的值
How can I loop through a csv file and replace values in it with a python dictionary
这是我的字典{'0':'Denver', '1':'Chicago', '2':'Maryland'}
在我的 csv 文件中
0 1
1 0
2 2
3 2
我想将 CSV 文件中的数字更改为字典中的值:
0 芝加哥
1 丹佛
2 马里兰州
3 马里兰州
d = {'0':'Denver', '1':'Chicago', '2':'Maryland'}
# we'll start by creating a new file to write the output to
with open("output_filename.csv", "w+") as out_file:
# So the first piece is reading the file in python
with open("filename.csv") as in_file:
# next you'll want to loop over each line
for line in in_file:
# Now we can split the string into elements by the whitespce
line_list = line.split(" ")
# line_list = ['0', '1', '1', '0', '2', '2', '3', '2']
# we can loop over the list taking alternating elements and looking them up
result = " ".join([d[item] if index % 2 else item for index, item in enumerate(line_list)])
out_file.write(result)
真正的“工作”发生在这一行:
result = " ".join([d[item] if index % 2 else item for index, item in enumerate(line_list)])
enumerate
returns 我们遍历 line_list 时的索引和值 所以 (0, '0'), (1, '1'), (2, '1') ...
然后车工正在使用模 %
来查看除以 2 时的余数(即如果索引为 0、2、4...)并使用字典查找如果 不是 的值(即索引 1、3、5...)
这是我的字典{'0':'Denver', '1':'Chicago', '2':'Maryland'}
在我的 csv 文件中 0 1 1 0 2 2 3 2 我想将 CSV 文件中的数字更改为字典中的值: 0 芝加哥 1 丹佛 2 马里兰州 3 马里兰州
d = {'0':'Denver', '1':'Chicago', '2':'Maryland'}
# we'll start by creating a new file to write the output to
with open("output_filename.csv", "w+") as out_file:
# So the first piece is reading the file in python
with open("filename.csv") as in_file:
# next you'll want to loop over each line
for line in in_file:
# Now we can split the string into elements by the whitespce
line_list = line.split(" ")
# line_list = ['0', '1', '1', '0', '2', '2', '3', '2']
# we can loop over the list taking alternating elements and looking them up
result = " ".join([d[item] if index % 2 else item for index, item in enumerate(line_list)])
out_file.write(result)
真正的“工作”发生在这一行:
result = " ".join([d[item] if index % 2 else item for index, item in enumerate(line_list)])
enumerate
returns 我们遍历 line_list 时的索引和值 所以 (0, '0'), (1, '1'), (2, '1') ...
然后车工正在使用模 %
来查看除以 2 时的余数(即如果索引为 0、2、4...)并使用字典查找如果 不是 的值(即索引 1、3、5...)