【问题标题】:Splitting lines by strings and integers in python from txt file [duplicate]从txt文件中的python中按字符串和整数分割行[重复]
【发布时间】: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


【解决方案1】:
>>> "give up -6".rsplit(" ", 1)
['give up', '-6']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 2011-08-19
    • 2014-07-16
    • 2019-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多