我正在嘗試基於文本文件創建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