如何从python中带有空格的.txt文件创建字典

2024-09-28 23:52:01 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我必须处理的.txt文件。无论如何,我无法在中更改文件

Avignon 48
Bordeaux -6
Brest -45
Caen -4
Calais 18

Dijon 51
Grenoble 57
Limoges 12
Lyon 48
Marseille 53

Montpellier 36
Nantes -16
Nancy 62
Nice 73
Paris 23

Rennes -17
Strasbourg 77
Toulouse 14

我在将此文件转换为字典时遇到问题。这是我目前正在尝试使用的方法

d = {}
when open("dict.txt") as f:
    for line in f:
        if line.endswith('\n'):
            (key, val) = line.split()
            d[key] = int(val)

        elif line.endswith('\n\n'):
            (key, val) = line.split()
            d[key] = int(val)
    print(d)

问题在于.txt文件中的文本集之间存在额外的空间。当没有多余的空格时,我可以创建字典而不会出现任何问题

Traceback (most recent call last):
  File "C:\Users\alexa\PycharmProjects\pythonProject4\Data.py", line 73, in 
  <module>
    (key, val) = line.split()
ValueError: not enough values to unpack (expected 2, got 0)

这就是我得到的错误。如何解决此问题


Tags: 文件keyintxt字典linevalint
1条回答
网友
1楼 · 发布于 2024-09-28 23:52:01

这里的问题是空行将是'\n',因此您无法区分空行和其他行,因为所有行都将以'\n'结尾。下面是我使用列表理解和for循环的建议。也许能在一次听写理解中做到

# Read in file
lines = []                                                                                                                         
with open('file.txt', 'r') as f: 
    lines = f.readlines()

# Split out and drop empty rows
strip_list = [line.replace('\n','').split(' ') for line in lines if line != '\n']

d = dict()
for strip in strip_list: 
    d[strip[0]] = int(strip[1]) 

输出:

{'Avignon': 48,
 'Bordeaux': -6,
 'Brest': -45,
 'Caen': -4,
 'Calais': 18,
 'Dijon': 51,
 'Grenoble': 57,
 'Limoges': 12,
 'Lyon': 48,
 'Marseille': 53,
 'Montpellier': 36,
 'Nantes': -16,
 'Nancy': 62,
 'Nice': 73,
 'Paris': 23,
 'Rennes': -17,
 'Strasbourg': 77,
 'Toulouse': 14}

相关问题 更多 >