1

我正在尝试将 CSV 文件中的数据存储在 python 变量中:

我有这个 CSV:

CountryName,  ChargeMinutes
Cape Verde ,    0.00
Algeria ,       10.80
St. Lucia ,     0.00
Cameroon ,      48.75
United States , 457,929.00

我需要为每个国家/地区创建一个变量并为其分配相同的名称并添加实际收费分钟,例如:

cape_verde = 0
algeria = 10
st_lucia = 0
cameroon = 48 
etc...

我已经有了 CSV 的输出,但我不知道如何将数据输出存储在变量中。

import csv

with open("datatmx_headers.csv", "r") as f_input:
    csv_input = csv.DictReader(f_input)

    for row in csv_input:
        country = row['CountryName']
        minutes = row['ChargeMinutes']
        print(country, minutes)
4

2 回答 2

0

我建议您创建一个字典并将其用作变量列表。这样,您可以在一个地方存储和跟踪所有变量信息。

var = {}
with open("datatmx_headers.csv", "r") as f_input:
    csv_input = csv.DictReader(f_input)

    for row in csv_input:
        var[row['CountryName']] = row['ChargeMinutes']

在此处输入图像描述

我希望这会有所帮助。

于 2020-05-24T02:21:06.457 回答
0

因此,在达到提议的目标之前,您需要做一些事情。由于您有“佛得角”、“圣卢西亚”、“阿尔及利亚”等特殊情况。

要处理字符串末尾有空格的“Cape Verde”和“Algeria”,您应该添加:

for row in csv_input:
    country = row['CountryName'.strip()]
    minutes = row['ChargeMinutes']
    print(country, minutes)

现在您将找不到末尾带有空格的国家/地区名称。然后我们应该处理包含“。”的名称。

for row in csv_input:
    country = row['CountryName'.strip().replace(".","")]
    minutes = row['ChargeMinutes']
    print(country, minutes)

Finally, we should remove white spaces between two word names like "Cape Verde" and replace it with "_".

for row in csv_input:
    country = row['CountryName'.strip().replace(".","").replace(" ","_")]
    minutes = row['ChargeMinutes']
    print(country, minutes)

And instead of having a variable for each country I suggest you to add all of them to a dictionary to have them in a single variable and easily access the data.

my_dict = {}
for row in csv_input:
    country = row['CountryName'.strip().replace(".","").replace(" ","_")]
    minutes = row['ChargeMinutes']
    my_dict[country] = minutes

After this you should be able to access data like this:

print(my_dict.algeria) #prints 10.80
print(my_dict.Cape_Verde) #prints 0.0
于 2020-05-24T02:25:57.673 回答