簡體   English   中英

來自具有特定結構的字符串的字典

[英]Dictionary from a String with particular structure

我正在使用 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=

你所擁有的是一個普通的屬性文件 您可以使用此示例將值讀入 map:

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 解決方案,請參閱已回答的問題
您可以使用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', ...}

我建議進行一些清潔以擺脫 [] 行。

之后,您可以用“=”分隔符拆分這些行,然后將其轉換為字典。

可以在 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)

Output:

{
  "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"
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM