【发布时间】:2021-07-01 03:37:53
【问题描述】:
所以我有一个 txt 文件,其中包含单词及其各自的分数作为每行中的整数。示例:
word_scores.txt:
放弃-2
接受+2
欢呼4
放弃-6
我试过这段代码:
d = {} #store in dictionary d
with open("word_scores.txt") as f:
for line in f:
(key, val) = line.split() #key = word, val = score
d[key] = int(val)
它工作正常,除非一行中有两个单词(例如,放弃)。在这种情况下,如何修改我的代码,以便它可以成功地将“放弃”作为键存储在字典中?
提前谢谢你
【问题讨论】:
-
line.split(None, 1)
标签: python dictionary txt