这是我必须使用的 .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)
这是我得到的错误。我该如何解决这个问题?
这里的问题是空行将是 '\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}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句