簡體   English   中英

從文檔中讀取行並將某些行存儲在字典/數組中 - python

[英]Reading lines from a document and storing certain lines in a dictionary/array - python

我有一個正在讀取行的文件。 使用 python 3.7

該文件是自動生成的,因此文件的格式如下所示:


    Computer #1 - gaming 
       spec 1 = something 
       spec 2 = something 
       spec 3 = something
       other stuff = sadas 
    computer #2 - coding 
       spec 1 = something 
       spec 2 = something 
       spec 3 = something 
       other stuff = sadas
    computer #n - etc 
       spec 1 = something 
       spec 2 = something 
       spec 3 = something 
       other stuff = sadas

我希望將信息存儲到字典/數組中:

數據= {“計算機#1”:[sepc1,spec2,spec3],“計算機#2”:[sepc1,spec2,spec3],“計算機#n”:[sepc1,spec2,spec3]}

lines = file_read.readlines()
for line in lines: 
    if 'computer #' in line: 
    data[line] = []
if 'spec1' in line:
    # here I want to add that value/line to the the first key/value such that: 
    # data['computer #1'].append(line)
    # data['computer #2'].append(line)
    # data['computer #n'].append(line)

我擁有的文件很大並且有相關信息。 上面的行只是為了說明我正在處理的內容

每次找到關鍵字(計算機#)時,我都嘗試添加一個計數器。 但我不確定如何檢查計數器更改的狀態,以便可以將所有“找到/需要”行(規格)添加到數組中。

花了太多時間試圖解決這個問題。 謝謝您的幫助。

如果spec可能與“其他東西”(作為字符串或另一個單詞的一部分)一起出現,則使用正則表達式匹配spec \d+ =模式可能更安全:

import re
data = {}

with open("file.txt", 'r') as f:
    for l in f.readlines():
        if 'computer #' in l:
            key = l.split('-')[0].strip()
            data[key] = []
        elif re.search(r'spec \d+ =', l):
            val = l.split('=')[0].strip()
            data[key].append(val)

print(data)

Output:

{'computer #1': ['spec 1', 'spec 2', 'spec 3'], 'computer #2': ['spec 1', 'spec 2', 'spec 3'], 'computer #n': ['spec 1', 'spec 2', 'spec 3']}

暫無
暫無

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

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