从Excel中的字符串列表中拆分列

时间:2015-10-14 14:30:44

标签: xml excel python-2.7 csv

我正在尝试基于文本文件创建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")

但是我当前的代码只是将所有内容堆叠到一列上。

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

2 个答案:

答案 0 :(得分:1)

摆脱&#34; for nameNames&#34;循环,更改为在打印行后使用此功能,然后您不需要列出列标题:

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

您遇到的问题是,每次通过&#34;对于setNames&#34;中的名称,您都要打开文件进行阅读。环。

答案 1 :(得分: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