【问题标题】:Splitting columns from a list of strings in Excel从 Excel 中的字符串列表中拆分列
【发布时间】:2015-10-14 14:30:44
【问题描述】:

我正在尝试基于文本文件创建 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 文件。目前这是我的代码,它可以工作,但是由于某种原因,我无法弄清楚格式,所以|&lt;Number1||&lt;Number2&gt;| 都在他们自己的列中,有自己的数据。像这样:

目前我正在使用以下代码:

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")

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

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

【问题讨论】:

  • 您可以添加一些查看每一行的代码,如果前 x 个字符是“

标签: xml excel python-2.7 csv


【解决方案1】:

摆脱“for names in setNames”循环,在“打印行”之后改为使用它,那么你就不需要列出你的列标题了:

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

您遇到的问题是,每次执行“for names in setNames”循环时,您都会打开文件进行读取。

【讨论】:

  • 当您说摆脱循环时,您是在说我的idx 循环对吗? for idx in range(len(lines)):
  • 删除任何引用名称或 setNames 的行
  • 再次感谢您!它工作得继续研究它试图理解为什么它比以前的代码有效
【解决方案2】:

运行这个 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

将产生:

【讨论】:

  • 我需要一种方法在创建 CVS 文件时自动执行此操作,而不是手动使用 Excel 中的内置宏。
  • @JeanP 然后忽略我的回复。
猜你喜欢
  • 1970-01-01
  • 2019-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-10
  • 2016-03-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多