【问题标题】:reading key and values into python dict from text从文本中将键和值读入 python dict
【发布时间】:2016-03-21 11:12:43
【问题描述】:

我有一个这种格式的文本文件。

the 0.418 0.24968 -0.41242 0.1217 0.34527 -0.044457 -0.49688 -0.17862 -0.00066023 -0.6566 0.27843 -0.14767 -0.55677 0.14658 -0.0095095 0.011658
and 0.26818 0.14346 -0.27877 0.016257 0.11384 0.69923 -0.51332 -0.47368 -0.33075 -0.13834 0.2702 0.30938 -0.45012 -0.4127 -0.09932 0.038085 

我想将它读入一个 python dict 变量,这样我就有了

{'the': [0.418, 0.24968,..], 'and': [0.26818 0.14346,..]}

我不知道如何开始?

【问题讨论】:

    标签: python file dictionary


    【解决方案1】:

    这是一个可行的解决方案:

    my_dict = {}
    with open('your_file_name') as f:
        for line in f:
            elements = line.split()
            my_dict[elements[0]] = [float(e) for e in elements[1:]]
    

    注意@CoryKramer 建议的解决方案使用readlines,它返回一个列表而不是迭代器。所以我不建议对大文件使用他的解决方案(这会不必要地占用太多内存)。

    【讨论】:

      【解决方案2】:

      您可以逐行遍历文件。然后split 在空白处,使用索引[0] 作为键,然后使用列表推导将剩余的值转换为float 的列表。

      with open(text_file) as f:
          d = dict()
          for line in f:
              data = line.split()
              d[data[0]] = [float(i) for i in data[1:]]
          print(d)
      

      输出

      {'and': [0.26818, 0.14346, -0.27877, 0.016257, 0.11384, 0.69923, -0.51332, -0.47368, -0.33075, -0.13834, 0.2702, 0.30938, -0.45012, -0.4127, -0.09932, 0.038085],
       'the': [0.418, 0.24968, -0.41242, 0.1217, 0.34527, -0.044457, -0.49688, -0.17862, -0.00066023, -0.6566, 0.27843, -0.14767, -0.55677, 0.14658, -0.0095095, 0.011658]}
      

      【讨论】:

        【解决方案3】:

        这是一个开始吗?

        import json
        
        variable_one = "the 0.418 0.24968 -0.41242 0.1217 0.34527 -0.044457 -0.49688 -0.17862 -0.00066023 -0.6566 0.27843 -0.14767 -0.55677 0.14658 -0.0095095 0.011658"
        
        variable_one = variable_one.split()
        json_variable_one = []
        json_variable_one = variable_one[0], variable_one[1:]
        
        print(json.dumps(json_variable_one))
        

        输出:

        [“the”,[“0.418”,“0.24968”,“-0.41242”,“0.1217”,“0.34527”,“-0.044457”,“-0.49688”,“-0.17862”,“-0.00066023”, “-0.6566”、“0.27843”、“-0.14767”、“-0.55677”、“0.14658”、“-0.0095095”、“0.011658”]]

        【讨论】:

          猜你喜欢
          • 2013-09-18
          • 1970-01-01
          • 2022-08-18
          • 2015-06-25
          • 1970-01-01
          • 2015-02-12
          • 2012-08-31
          • 2019-07-20
          • 2022-01-10
          相关资源
          最近更新 更多