2011-04-01 71 views
1

我怎會將在Python如下: 我有一個命令的輸出,其輸出這樣的:Python入門:在字典存儲值在標準輸出

Datexxxx 
Clientxxx 
Timexxx 

Datexxxx 
Client2xxx 
Timexxx 

Datexxxx 
Client3xxx 
Timexxx 

而且我要來解決這個在字典一樣:

Client:(date,time), Client2:(date,time) ... 
+0

你到現在爲止提出了什麼?如果沒有,請嘗試從_stdin_讀取某些內容並將其存儲在一個變量中並將其打印到_stdout_。 – 2011-04-01 14:41:31

+1

datetime.datetime可能是一種更好的格式來存儲日期和時間,雖然strptime不會對'xxxx'做任何有用的操作。實際的格式是什麼樣的? – geoffspear 2011-04-01 14:41:47

+0

請發佈輸出的代碼。瞭解它目前的工作情況非常重要,以便我們可以根據需要對其進行修改。 – jhocking 2011-04-01 14:49:34

回答

1

將數據讀入一個字符串subject後,你可以這樣做:

import re 
d = {} 
for match in re.finditer(
    """(?mx) 
     ^Date(.*)\r?\n 
     Client\d*(.*)\r?\n 
     Time(.*)""", 
    subject): 
     d[match.group(2)] = (match.group(1), match.group(2)) 
+0

謝謝,我認爲這是我現在需要的! – 2011-04-01 14:48:52

1

如何使用帶元組的字典? 創建一個詞典並添加條目:

dict = {} 
dict['Client'] = ('date1','time1') 
dict['Client2'] = ('date2','time2') 

訪問entires:

dict['Client'] 
>>> ('date1','time1') 
+0

好的,但我想用輸出做到這一點!不是手動的 – 2011-04-01 14:40:10

+0

好的。我誤解了你的問題。 – tgmath 2011-04-01 14:50:28

+0

沒問題!無論如何謝謝 – 2011-04-01 14:51:19

1

怎麼樣例如:

rows = {} 
thisrow = [] 

for line in output.split('\n'): 
     if line[:4].lower() == 'date': 
       thisrow.append(line) 
     elif line[:6].lower() == 'client': 
       thisrow.append(line) 
     elif line[:4].lower() == 'time': 
       thisrow.append(line) 
     elif line.strip() == '': 
       rows[thisrow[1]] = (thisrow[0], thisrow[2]) 
       thisrow = [] 

print rows 

假設一個尾隨的換行符,行之前沒有空格,等等。

+0

感謝您的回答 – 2011-04-01 14:49:47