在Excel中从string列表中分割列

我正在尝试创build基于文本文件的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 | 

我的目标是用这些数据创build一个.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") 

不过,我现在的代码只是将所有东西堆叠到一个列上。

如何编辑我的代码,以便当我到达列表中的下一个条目时,它会创build一个新列?

摆脱“在setNames名称”循环,更改为“打印行”后使用此,那么你不需要列出你的列标题:

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

您遇到的问题是您每次打开“setNames中的名称”循环时都打开文件。

运行这个VBAmacros:

 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 

会产生:

在这里输入图像说明