I've been working on scraping web data and I'm having trouble converting the base data into an array of arrays with a fixed size of 3. Another method would be parsing each method seperatly, but that's not ideal.
The text file/string is as follows
NAME[1]
DATE[1]
ITEMS[1]
PRICE[1]
NAME[2]
DATE[2]
ITEMS[2]
PRICE[2]
NAME[3]
DATE[3]
ITEMS[3]
PRICE[3]
NAME[4]
DATE[4]
ITEMS[4]
PRICE[4]
NAME[5]
DATE[5]
ITEMS[5]
PRICE[5]
NAME[6]
DATE[6]
ITEMS[6]
PRICE[6]
So far I've split it using
arr = value.split(',')
print(arr)
My desired outcome would be an output like this
[[
NAME[1]
DATE[1]
ITEMS[1]
PRICE[1]
][
NAME[2]
DATE[2]
ITEMS[2]
PRICE[2]
][
NAME[3]
DATE[3]
ITEMS[3]
PRICE[3]
],...
]
What would be the best way to get this outcome?
CodePudding user response:
This works for me:
lines = []
with open('something.txt') as f:
for line in f.readlines():
lines.append(line.strip())
To make the final list:
final_list = []
for i in range(0, len(lines), 4):
final_list.append([lines[i], lines[i 1], lines[i 2], lines[i 3]])
The Output:
final_list
[['NAME[1]', 'DATE[1]', 'ITEMS[1]', 'PRICE[1]'],
['NAME[2]', 'DATE[2]', 'ITEMS[2]', 'PRICE[2]'],
['NAME[3]', 'DATE[3]', 'ITEMS[3]', 'PRICE[3]'],
['NAME[4]', 'DATE[4]', 'ITEMS[4]', 'PRICE[4]'],
['NAME[5]', 'DATE[5]', 'ITEMS[5]', 'PRICE[5]'],
['NAME[6]', 'DATE[6]', 'ITEMS[6]', 'PRICE[6]']]