【问题标题】:Dictionary from a String with particular structure来自具有特定结构的字符串的字典
【发布时间】:2020-02-18 17:12:21
【问题描述】:

我正在使用 python 3 读取此文件并将其转换为字典。

我有一个文件中的这个字符串,我想知道如何从它创建一个字典。

[User]
Date=10/26/2003
Time=09:01:01 AM
User=teodor
UserText=Max Cor
UserTextUnicode=392039n9dj90j32

[System]
Type=Absolute
Dnumber=QS236
Software=1.1.1.2
BuildNr=0923875
Source=LAM
Column=OWKD

[Build]
StageX=12345
Spotter=2
ApertureX=0.0098743
ApertureY=0.2431899
ShiftXYZ=-4.234809e-002

[Text]
Text=Here is the Text files
DataBaseNumber=The database number is 918723

.....(每个文件超过 1000 行)...

在文本上我有"Name=Something",然后我想将其转换如下:

{'Date':'10/26/2003',
'Time':'09:01:01 AM'
'User':'teodor'
'UserText':'Max Cor'
'UserTextUnicode':'392039n9dj90j32'.......}

[ ]之间的单词可以去掉,比如[User], [System], [Build], [Text], etc...

在某些字段中只有字符串的第一部分:

[Colors]
Red=
Blue=
Yellow=
DarkBlue=

【问题讨论】:

    标签: python string dictionary


    【解决方案1】:

    你拥有的是一个普通的properties file。您可以使用此示例将值读入地图:

    try (InputStream input = new FileInputStream("your_file_path")) {
        Properties prop = new Properties();
        prop.load(input);
    
        // prop.getProperty("User") == "teodor"
    
    } catch (IOException ex) {
      ex.printStackTrace();
    }
    

    编辑:
    Python解决方案请参考the answerred question
    您可以使用configparser 读取.ini.properties 文件(您拥有的格式)。

    import configparser
    
    config = configparser.ConfigParser()
    config.read('your_file_path')
    
    # config['User'] == {'Date': '10/26/2003', 'Time': '09:01:01 AM'...}
    # config['User']['User'] == 'teodor'
    # config['System'] == {'Type': 'Abosulte', ...}
    

    【讨论】:

    【解决方案2】:

    我建议进行一些清理以摆脱 [] 行。

    之后,您可以用“=”分隔符拆分这些行,然后将其转换为字典。

    【讨论】:

      【解决方案3】:

      可以很容易地在 python 中完成。假设您的文件名为test.txt。 这也适用于= 之后没有任何内容的行以及具有多个= 的行。

      d = {}
      with open('test.txt', 'r') as f:
          for line in f:
              line = line.strip() # Remove any space or newline characters
              parts = line.split('=') # Split around the `=`
              if len(parts) > 1:
                  d[parts[0]] = ''.join(parts[1:])
      print(d)
      

      输出:

      {
        "Date": "10/26/2003",
        "Time": "09:01:01 AM",
        "User": "teodor",
        "UserText": "Max Cor",
        "UserTextUnicode": "392039n9dj90j32",
        "Type": "Absolute",
        "Dnumber": "QS236",
        "Software": "1.1.1.2",
        "BuildNr": "0923875",
        "Source": "LAM",
        "Column": "OWKD",
        "StageX": "12345",
        "Spotter": "2",
        "ApertureX": "0.0098743",
        "ApertureY": "0.2431899",
        "ShiftXYZ": "-4.234809e-002",
        "Text": "Here is the Text files",
        "DataBaseNumber": "The database number is 918723"
      }
      

      【讨论】:

      • 如果它解决了答案,别忘了标记它是一个答案:)。虽然配置解析器的支付效果更好。
      猜你喜欢
      • 2015-10-21
      • 1970-01-01
      • 2020-11-03
      • 2020-10-29
      • 2014-10-27
      • 2012-12-29
      • 2021-12-11
      • 1970-01-01
      • 2017-02-20
      相关资源
      最近更新 更多