这是我必须处理的.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循环的建议。也许能在一次听写理解中做到
输出:
相关问题 更多 >
编程相关推荐