具有特定结构的字符串的字典

2024-06-01 05:13:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python3读取这个文件并将其转换为字典

我有一个文件中的字符串,我想知道怎样才能从中创建一个字典

[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=

Tags: 文件字符串textbuilddate字典timeam
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"
}

我建议你做些清洁以去除这些线

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

你拥有的是一个普通的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', ...}

相关问题 更多 >