我正在尝试基于文本文件创建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>|
与他们自己的数据在自己的专栏。事情是这样的:
目前我使用下面的代码:
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个字符是“<数字”,则向右移动一列。 (对不起,我不太了解python) – BruceWayne