2015-10-14 61 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然后忽略我的回应。 –