2011-10-13 257 views
1

使用正則表達式我正在通過包含數據的文本文件進行搜索。我得到類似這樣的輸出。 這是我得到例如:Python將多行寫入數組

36 
37 
36 
36 
36 
76 
39 
36 
68 
36 
56 
36 
36 
36 
... 

我需要所有這些36是在陣列像這樣[「36」,「36」,...]示例代碼的下方。

#!/usr/bin/python 

import re 

log = re.compile('Deleted file number: first: (\d+), second (\d+), third (\d+), fourth (\d+), bw (\d+), value: ([\dabcdefx]+), secondvalue: ([\d.]+)LM, hfs: ([\d.-]+)ls') 

logfile = open("log.txt", "r").readlines() 

List = [] 

for line in logfile: 
    m = log.match(line) 
    if m: 
     first  = int (m.group(1)) 
     second  = int (m.group(2)) 
     third  = int (m.group(3)) 
     fourth  = int (m.group(4)) 
     bw   = int (m.group(5)) 
     value  = int (m.group(6),0) 
     secondvalue = float (m.group(7)) 
     hfs   = float (m.group(8)) 

     List.append(str(first)+","+str(second)+"," \ 
        +str(third)+","+str(fourth)+"," \ 
        +str(bw)+","+str(value)+"," \ 
        +str(secondvalue)+","+str(hfs)) 

for result in List: 
    print(result) 

我可以使用sys.stdout.write函數()來在一個單一的線路相同的帶有打印內容的項目, 顯示它可是我怎樣才能把所有這一切成一個陣列,以像陣列= [「149」, 149" , 「153」, 「153」 等]

任何幫助,將不勝感激

+2

從驗證碼的相關摘錄會幫助我們。您可以創建一個列表併爲其添加每個值。 –

+0

我得不到字符串,但是列 – user993298

+0

當你將它們作爲字符串保存到數組中時,爲什麼要將它們轉換爲int和float。一個數組可以簡單[第一,第二,第三,...] – spicavigo

回答

0

假設你有什麼是字符串:

'"149" "149" "153" "153" "159" "159" "165" "165" "36" "36" "44"' 

(目前還不清楚,你怎麼是獲取數據的機智哈正則表達式,因爲你沒有表示不代碼),使用

[x.strip('"') for x in '"149" "149" "153" "153" "159" "159" "165" "165" "36" "36" "44"'.split()] 

得到列表(不陣列,這是另一回事):

['149', '149', '153', '153', '159', '159', '165', '165', '36', '36', '44'] 

如果你真的想數組(它只能存儲數值,而不是數字的字符串表示這是你展示,用什麼):

import array 
foo = array.array('i',(int(x.strip('"')) for x in '"149" "149" "153" "153" "159" "159" "165" "165" "36" "36" "44"'.split())) 
5

ÿ我們的數據已經在列表中。與此

for result in List: 
    print(result) 

:如果你要打印出來的數組符號,更換此

print List 

你真的不應該打電話給你的列表List,雖然 - list是一個保留字,並List混淆相似。

順便說一句,這一點:

List.append(str(first)+","+str(second)+"," \ 
       +str(third)+","+str(fourth)+"," \ 
       +str(bw)+","+str(value)+"," \ 
       +str(secondvalue)+","+str(hfs)) 

更加理解,如果你使用其他Python功能,如加入:

List.append(",".join([first, second, third, fourth, bw, value, secondvalue, hfs])) 

事實上,因爲你的變量是從正則表達式剛組,你可以縮短整個事情:

List.append(",".join(m.groups())) 
+0

感謝您的明確答案,現在我明白了:) – user993298

1

你有沒有試過:

print List 

如果你想在一個字符串:

result = str(List) 
+0

我同意@Nick Johnson的命名問題。 –

+0

並提出了他的答案,因爲他的「團體」建議會讓你的代碼更容易閱讀。 –