如何从.t​​xt文件在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('nn'):
            (key, val) = line.split()
            d[key] = int(val)
    print(d)

问题是当 .txt 文件中的文本集之间有额外的空间时。当没有多余的空格时,我可以毫无问题地创建字典。

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

这是我得到的错误。我该如何解决这个问题?

回答

这里的问题是空行将是 '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}


以上是如何从.t​​xt文件在python中创建一个带有空格的字典的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>