【问题标题】:convert vertical .txt file to dictionary without any library just python basic function将垂直 .txt 文件转换为字典,无需任何库,只需 python 基本功能
【发布时间】:2021-04-17 07:49:35
【问题描述】:

如何转换这个 .txt 文件 txt file

到这个 dictionary

这是我的代码 输入:


file_harga_rumah = open("harga_rumah.txt", "r")
data_harga_rumah = file_harga_rumah.read()
file_harga_rumah.close()

key_harga_rumah = data_harga_rumah.replace("\n",",").split(",")
harga_rumah = []
for baris in key_harga_rumah:
    baris_harga_rumah = baris
    dict_harga_rumah = dict()
    for i in range(len(baris_harga_rumah)):
        harga_rumah[key_harga_rumah[i]] = dict_harga_rumah
    harga_rumah.append(harga_rumah[key_harga_rumah[i]])

输出:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-115-aeb7087f0ba0> in <module>
      9     dict_harga_rumah = dict()
     10     for i in range(len(baris_harga_rumah)):
---> 11         harga_rumah[key_harga_rumah[i]] = dict_harga_rumah
     12     harga_rumah.append(harga_rumah[key_harga_rumah[i]])

TypeError: list indices must be integers or slices, not str

我无法将此 txt 文件转换为字典,请帮忙:))))

【问题讨论】:

  • 请更新您的问题并上传您的代码,但不要上传照片

标签: python dictionary txt


【解决方案1】:

示例:

你可以使用dictReader:

input_file = csv.DictReader(open(r'c:\temp\file.txt'))

显示结果:

for row in input_file:
    print(row)

结果:

【讨论】:

    【解决方案2】:

    我有一种方法可以让您在不使用任何导入语句的情况下完成此操作。它可能会让您感到困惑,但效果很好

    这里是如何做到这一点

    文本文件:

    col1,col2,col3
    1,2,3
    2,3,4
    4,5,6
    7,8,9
    

    功能

    def get_dict(file_name):
        with open(file_name) as fl:
            txt = fl.read()
        rows = txt.split('\n')
        columns = rows[0].split(',')
        data = []
        for value in rows[1:]:
            temp = {}
            for key in columns:
                temp[key] = value.split(',')[columns.index(key)]
        return data
    

    输入

    file_name = "file.txt"
    data = get_dict(file_name)
    

    输出

    >>> data
    [{'col1': '1', 'col2': '2', 'col3': '3'}, {'col1': '2', 'col2': '3', 'col3': '4'}, {'col1': '4', 'col2': '5', 'col3': '6'}, {'col1': '7', 'col2': '8', 'col3': '9'}]
    

    注意:如果您使用带逗号(,)的空格,请使用 strip() 例如。 text.strip() 删除文本开头和结尾的多余空格。

    【讨论】:

      【解决方案3】:

      输入文件:

      tanah,bangunan,jarak_ke_pusat,harga
      70,50,15,500
      70,60,30,400
      70,60,55,300
      100,50,30,700
      100,70,25,1000
      100,70,50,650
      120,100,20,2000
      120,80,50,1200
      150,100,50,1800
      150,90,15,3000
      

      像这样解析文件:

      from pprint import pprint
      
      with open('harga_rumah.txt', 'r') as f:
          rows = [row.rstrip() for row in f]
      
      output_list = []
      heading_list = rows[0].split(',')
      for row in rows[1:]:
          row_dict = {}
          for heading in heading_list:
              row_dict[heading] = row.split(',')[heading_list.index(heading)]
          output_list.append(row_dict)
      
      pprint(output_list)
      

      输出:

      [{'bangunan': '50', 'harga': '500', 'jarak_ke_pusat': '15', 'tanah': '70'},
       {'bangunan': '60', 'harga': '400', 'jarak_ke_pusat': '30', 'tanah': '70'},
       {'bangunan': '60', 'harga': '300', 'jarak_ke_pusat': '55', 'tanah': '70'},
       {'bangunan': '50', 'harga': '700', 'jarak_ke_pusat': '30', 'tanah': '100'},
       {'bangunan': '70', 'harga': '1000', 'jarak_ke_pusat': '25', 'tanah': '100'},
       {'bangunan': '70', 'harga': '650', 'jarak_ke_pusat': '50', 'tanah': '100'},
       {'bangunan': '100', 'harga': '2000', 'jarak_ke_pusat': '20', 'tanah': '120'},
       {'bangunan': '80', 'harga': '1200', 'jarak_ke_pusat': '50', 'tanah': '120'},
       {'bangunan': '100', 'harga': '1800', 'jarak_ke_pusat': '50', 'tanah': '150'},
       {'bangunan': '90', 'harga': '3000', 'jarak_ke_pusat': '15', 'tanah': '150'}]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-20
        • 2017-07-28
        • 2020-12-16
        • 2023-03-15
        • 2011-02-04
        • 2019-05-26
        • 2019-10-28
        • 2015-07-13
        相关资源
        最近更新 更多