2015-10-14 60 views
0

我正在嘗試基於文本文件創建Excel文檔。這是我的文本文件的例子:在Excel中分割字符串列表中的列

example.txt中

|<Number1>| 
    |TREE= 800 | 
    |BIRD = 500 | 
    |FISH = 25 | 
    |DOG = 10 | 
    |CAT = 5 | 
    |ANOTHERCAT = 800 | 
    |THERESOMANYCATS = 3 | 
    |HAMSTER = 5 | 
|<Number2>| 
    |TREE= 800 | 
    |BIRD = 500 | 
    |FISH = 25 | 
    |DOG = 10 | 
    |CAT = 5 | 
    |ANOTHERCAT = 800 | 
    |THERESOMANYCATS = 3 | 
    |HAMSTER = 5 | 

我的目標是建立與數據.csv文件。目前這是我的代碼,它的工作原理,但由於某些原因,我不能找出格式,以便|<Number1||<Number2>|與他們自己的數據在自己的專欄。事情是這樣的:

excel1

目前我使用下面的代碼:

import re 

setNames = ['|<Number1>|', '|<Number2>|'] 

for names in setNames: 
    # Strip all spaces and dump all data into an array 
    lines = [mo for mo in re.findall('(?s)(?<=\|)([<\w].+?)\s+?\|', open('numbers.txt').read())] 
    # Create an array to hold the transformation 
    print lines 
    combined = ['' for x in range(len(lines)/lines.count(names[1:]))] 
    print names[1:] 
    # Append by rows 
    for idx in range(len(lines)): 
     combined[idx % len(combined)] += lines[idx] + ',' 

    # Write array to file 
    output = open('numbersConverted2.csv','wb') 
    for comb in combined: 
     output.write(comb + "\n") 

但是我當前的代碼只是堆棧上的一切一列。

如何編輯我的代碼,以便當我到達列表中的下一個條目時,它會創建一個新列?

+0

您可以添加一些代碼查看每行,如果前x個字符是「<數字」,則向右移動一列。 (對不起,我不太瞭解python) – BruceWayne

回答

1

獲得 「在setNames的名稱」 擺脫循環,改變後使用「打印行「,那麼你不需要列出你的列標題:

columns = sum([x.find('<')>=0 for x in lines]) 
combined = ['' for x in range(len(lines)/columns)] 

您遇到的問題是,您每次通過「for setNames中的名稱」循環時都會打開文件。

+0

當你說擺脫循環你說我的'idx'循環正確嗎? '對於範圍內的idx(len(行)):' – JeanP

+0

擺脫任何引用名稱或setNames – ergonaut

+0

的行再次謝謝!它的工作將繼續研究它試圖理解爲什麼這對以前的代碼有效 – JeanP

0

運行此VBA宏:

Sub NotPython() 
    Dim iCol As Long, iRow As Long, pipe As String 
    Dim TextLine As String 
    iCol = 0 
    iRow = 1 
    pipe = "|" 

    Close #1 
    Open "C:\TestFolder\input.txt" For Input As #1 

    Do While Not EOF(1) 
     Line Input #1, TextLine 
     TextLine = Trim(Replace(TextLine, pipe, "")) 
     If InStr(1, TextLine, "Number") > 0 Then 
     iRow = 1 
     iCol = iCol + 1 
     End If 
     Cells(iRow, iCol) = TextLine 
     iRow = iRow + 1 
    Loop 
End Sub 

會產生:

enter image description here

+0

我需要一種方法在創建CVS文件時自動執行此操作,而不是手動使用Excel中的內置宏。 – JeanP

+0

@JeanP然後忽略我的迴應。 –