无法将具有数字(字符串)的文件读入具有整数值的字典中

时间:2018-11-30 06:27:01

标签: python list file dictionary set

所以我有一个data.txt文件,其中包含有关汽车的信息:

CAR|PRICE|RPM

TOYOTA|21,000|3,600

HONDA|19,000|4,000

然后通过将此数据文件传递到函数createCarDictionary中,我可以创建一个字典,该字典创建汽车品牌作为键,并将值作为存储在列表中的txt文件中的剩余信息:

dict1 = {}

def createCarDictionary(datafile):
    for line in datafile.splitlines():
        line = line.replace(',', '')
        key, value, value2 = map(str.strip, line.split('|'))
        dict1[key] = [value, value2]
    return dict1

datafile = open('data.txt', 'r').read()

createCarDictionary(datafile)
print(dict1)

输出

{'HONDA': ['19000', '4000'], 'TOYOTA': ['21000', '3600'], 'CAR': ['PRICE', 'RPM']}

我正在尝试使用上述函数中的for循环将txt文件中的数字转换为整数,但是由于标头CAR|PRICE|RPM for循环的原因,我收到了错误消息第一次使我的程序崩溃,因为标头无法在任何地方转换为整数。

如何使用上面的函数在dict1中将RPM和PRICE转换为整数,同时避免从最终结果中删除标头?

3 个答案:

答案 0 :(得分:0)

使用next语句打开文件后,可以使用with跳过第一行。

例如:

dict1 = {}

def createCarDictionary(datafile):
    with open(datafile) as infile:
        next(infile)  #Skip First Line
        for line in infile:
            line = line.replace(',', '')
            key, value, value2 = map(str.strip, line.split('|'))
            dict1[key] = [value, value2]
        return dict1

createCarDictionary('data.txt')
print(dict1)

答案 1 :(得分:0)

您可以使用以下代码:

<closureWarningLevels>
    <es5Strict>OFF</es5Script>
</closureWarningLevels>

答案 2 :(得分:0)

您可以使用 isdigit 方法检查字符串是否仅由数字组成

dict1 = {}
def check_string_and_get_number(value):
    if value.isdigit():
       return int(value)
    else:
       return value
def createCarDictionary(datafile):
    for line in datafile.splitlines():
        line = line.replace(',', '')
        key, value, value2 = map(str.strip, line.split('|'))
        value = check_string_and_get_number(value)
        value2 = check_string_and_get_number(value2)
        dict1[key] = [value, value2]
    return dict1

datafile = open('data.txt', 'r').read()

createCarDictionary(datafile)
print(dict1)