【发布时间】: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 文件。目前这是我的代码,它可以工作,但是由于某种原因,我无法弄清楚格式,所以|<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 个字符是“
标签: xml excel python-2.7 csv