我有一个txt文件,格式如下:Monday, Jul 24
8:45 apple 1
school
ball
dog
8:50 poirot 2
rouge
chien
chat
8:55 football 3
asroma
juventus
inter
如何将这些值放入csv而忽略第一行(星期一,7月24日)并在每行中插入实际日期?。我需要这种格式:
^{pr2}$
所以我想把它们放在这个格式。
这里是我的实际代码:import urllib2
import unicodecsv as csv
import os
import sys
import io
import time
import datetime
import pandas as pd
from bs4 import BeautifulSoup
import sys
import re
#def to_2d(l,n):
# return [l[i:i+n] for i in range(0, len(l), n)]
with open('air.txt', 'r') as f:
x = f.read()
print x
req_text = x.split('Test')[1: -1]
data = []
for text in req_text:
text = text.split('\n', 1)[1]
for line in text.strip().splitlines():
data.append([line])
#maindatatable = to_2d(data, 4)
with open('output.csv', "wb") as f:
output = csv.writer(f, delimiter=';',quotechar = '"', quoting=csv.QUOTE_NONNUMERIC, encoding='latin-1')
output.writerows(data)
f.close()
我试过用to_2d(l,n),但它不起作用,你知道我怎样才能用实际日期达到这种格式吗?[Python 2.7]
已更新代码,仍不起作用:
import urllib2
import unicodecsv as csv
import os
import sys
import io
import time
import datetime
import pandas as pd
from bs4 import BeautifulSoup
import sys
import re
def to_2d(l,n):
return [l[i:i+n] for i in range(0, len(l), n)]
with open('air.txt', 'r') as f:
x = f.read()
print x
req_text = x.split('Load')[1: -1]
data = []
for text in req_text:
text = text.split('\n', 1)[1]
for line in text.strip().splitlines():
data.append([line])
#maindatatable = to_2d(data, 4)
from string import ascii_uppercase as LETTERS
with open('air.txt') as f, open('output.csv', 'wb') as g:
actual_date = f.readline().strip()
while True:
first_line = f.readline().strip()
if not first_line:
break
second_line = f.readline().strip()
third_line = f.readline().strip()
fourth_line = f.readline().strip()
the_time, noun, number = first_line.split(' ')
number = int(number)
letter = LETTERS[number]
new_line = '%s1:%s %s %s %s2:%s %s3:%s %s4:%s %s5:%s' % (letter, the_time, noun, number, letter, second_line, letter, third_line, letter, fourth_line, letter, actual_date)
print (new_line)
f.close()