为了账号安全,请及时绑定邮箱和手机立即绑定

将文本文件读取为 dict

将文本文件读取为 dict

森栏 2021-12-09 11:00:05
我的文本文件看起来像这样..每行由一个空格分隔。dream 4.345 0.456 6.3456play 0.1223 -0.345 5.3543faster 1.324 2.435 -2.2345我想写字典并将其打印如下...dream: [4.345 0.456 6.3456]play: [0.1223 -0.345 5.3543]faster: [1.324 2.435 -2.2345]我的代码如下。请纠正我这个...with open("text.txt", "r") as file:     for lines in file:        line = lines.split()        keys = b[0]         values = b[1:]        d[keys] = valuesprint d
查看完整描述

3 回答

?
青春有我

TA贡献1784条经验 获得超8个赞

对于 python3,如果你想得到想要的结果:


d = {}


with open("text.txt", "r") as file:

    for lines in file:

    line = lines.split()

    keys = line[0] 

    values = list(map(float, line[1:]))

    d[keys] = values

for k in d :

    print(k , d[k])


查看完整回答
反对 回复 2021-12-09
?
元芳怎么了

TA贡献1798条经验 获得超7个赞

你可以这样试试。


输入.txt


dream 4.345 0.456 6.3456

play 0.1223 -0.345 5.3543

faster 1.324 2.435 -2.2345

编写器.py


output_text = '' # Text

d = {} # Dictionary


with open("input.txt") as f:

    lines = f.readlines()


    for line in lines:

        line = line.strip()

        arr = line.split()

        name = arr[0]

        arr = arr[1:]


        d[name] = arr

        output_text += name + ": [" + ' '.join(arr) + "]\n"


output_text = output_text.strip() # To remove extra new line appended at the end of last line


print(d)

# {'play': ['0.1223', '-0.345', '5.3543'], 'dream': ['4.345', '0.456', '6.3456'], 'faster': ['1.324', '2.435', '-2.2345']}


print(output_text)

# dream: [4.345 0.456 6.3456]

# play: [0.1223 -0.345 5.3543]

# faster: [1.324 2.435 -2.2345]


with open("output.txt", "w") as f:

    f.write(output_text)

输出.txt


dream: [4.345 0.456 6.3456]

play: [0.1223 -0.345 5.3543]

faster: [1.324 2.435 -2.2345]


查看完整回答
反对 回复 2021-12-09
?
萧十郎

TA贡献1815条经验 获得超13个赞

这很简单。请参阅下面的代码。


  dictionary = {}

  with open("text.txt", "r") as file:  

      for lines in file:

          line = lines.split()

          dictionary[line[0]] = line[1:]

  print(dictionary)


查看完整回答
反对 回复 2021-12-09
  • 3 回答
  • 0 关注
  • 252 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信