如何使用第一行作为关键字从文本文件制作字典

问题描述 投票:0回答:2

我正在尝试从文本文件到字典进行COVID监视,以检查每个国家/地区的情况。我想用这种格式制作字典。

covid ={country{confirmed:value, active:value, recovered:value, suspect:value, probable:value, 
deceased:value}

基于此文本文件。

 COUNTRY, CONFIRMED, ACTIVE, RECOVERED, SUSPECT, PROBABLE, DECEASED
 COUNTRY-A,3,4,2,1,0,0
 COUNTRY-B,1,2,0,2,0,0
 COUNTRY-C,4,2,0,0,3,0
 COUNTRY-D,1,1,1,3,0,0
 COUNTRY-E,3,2,0,2,0,0
 COUNTRY-F,2,0,1,2,0,0
 COUNTRY-G,0,0,1,4,0,0

我尝试过此代码,但它会打印COUNTRY,确认,活动,已恢复,可疑,可能,已减少每当我计算每个国家的案件总数时,都会给我一个错误。

我尝试过此代码:

def covid_monitoring():
country = []
cov_dict = {}
no_cases = []
with open("covidmonitor.txt", 'r') as f:

    for cov in f:
        cov = cov.strip()
        next(f)  # skip header
        if len(cov) >= 1:
            cov_line = cov.split(",")
            country.append(cov_line[0].strip())
            confirmed_file = cov_line[0].strip()
            active_file = cov_line[1].strip()
            recovered_file = cov_line[2].rstrip()
            suspected_file = cov_line[3].strip()
            probable_file = cov_line[4].strip()
            probable_file = cov_line[5].strip()
            deceased_file = cov_line[6].strip(';')
            if confirmed_file not in cov_dict:
                cov_dict[confirmed_file] = [(active_file,  recovered_file, suspected_file, probable_file, probable_file, deceased_file)]
            else:
                cov_dict[confirmed_file].append((active_file, recovered_file, suspected_file, probable_file, probable_file, deceased_file))
   # print(cov_dict)
for cntry in country:
    if cntry in cov_dict:
        for confirm, active, recovered, suspect, probable, deceased in cov_dict[cntry]:
            print("\tCOUNTRY:{cntry}")
            print("\tCONFIRMED:{confirm} ")
            print("\tACTIVE:{active} ")
            print("\tRECOVERED:{recovered} ")
            print("\tSUSPECTED:{suspect} ")
            print("\tPROPBABLE:{probable} ")
            print("\tDECEASED:{deceased} ")
            total_count = int(confirm) + int(active) + int(recovered) + int(suspect) + int(probable) + int(deceased)

            no_cases.apped(total_count)
            print(sum(no_cases)

这是我的错误:

     total_count = int(confirm) + int(active) + int(recovered) + int(suspect) + int(probable) + int(deceased)
     ValueError: invalid literal for int() with base 10: 'CONFIRMED'

保持所有人的安全!

python text key-value delimited-text
2个回答
0
投票

[通过查看代码,no_cases是字符串的列表,因为confirmactiverecoveredsuspectprobabledeceased都是字符串,而>>

total_count= (confirm + active + recovered + suspect + probable + deceased)

也是一个字符串,是串联而不是总和。

在代码的最后一行在字符串列表上调用sum()会产生如下错误:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

如果要将它们视为数字,则应将所有这些都转换为整数。


您的代码也存在其他问题。例如,您调用next(f)来跳过标题,但实际上是在for循环内在文件中的行上进行的,因此它很可能会跳过其他所有行。


0
投票

解析文件时,它始终是字符串。因此,您必须将每个值解析为float或int。


0
投票

您可以为此使用Python pandas包:

© www.soinside.com 2019 - 2024. All rights reserved.