Read special text file

조회 수: 6 (최근 30일)
Simon REMY
Simon REMY 2018년 10월 14일
댓글: Star Strider 2018년 10월 15일
Hi, guys. I'm trying to convert a python file in Matllab but I have a really hard time doing it since I don't have skills in Python and I'm not realy at ease with Matlab. The python code looks like that :
def LoadConsumptionData(filename):\n",
" dpm = [0,31,28,31,30,31,30,31,31,30,31,30]\n",
" ConsoData = open(filename, 'r')\n",
" Buf = ConsoData.readlines()\n",
" n_lines = len(Buf)\n",
" dt = 0.25\n",
" n_step = int(24. / dt)\n",
" n_days = int(n_lines/n_step)\n",
" P_elec = np.zeros((n_step,n_days), dtype=float)\n",
" date = np.arange(0,n_days)\n",
" time = np.arange(0,24,dt)\n",
" j = 0 # index for the time\n",
" k = 0 # index for the day\n",
" for i in range(n_lines-1):\n",
" (Buf1, Buf2, Buf3) = Buf[i+1].split(',')\n",
" (tmp1, tmp2) = Buf1.split(' ')\n",
" (yy, mm, dd) = tmp1.split('-')\n",
" (h, m, s) = tmp2.split(':')\n",
" t_float = float(h)+float(m)/60.+float(s)/3600.\n",
" j, = np.where(time==t_float)\n",
" k = int(dd)-1+np.sum(dpm[0:int(mm)])\n",
" P_elec[j,k] = float(Buf2)\n",
" return time, date, P_elec\n",
And the txt file looks like that (complete in attachment) :
Date,Total kW, Total kW Moy 15mn
2016-01-01 00:00:00,168,
2016-01-01 00:00:00,160,
2016-01-01 00:15:00,162,
2016-01-01 00:30:00,179,
2016-01-01 00:45:00,181,
2016-01-01 01:00:00,171,
2016-01-01 01:15:00,176,
2016-01-01 01:30:00,191,
2016-01-01 01:45:00,164,
2016-01-01 02:00:00,163,
2016-01-01 02:15:00,173,
2016-01-01 02:30:00,171,
2016-01-01 02:45:00,173,
2016-01-01 03:00:00,173,
2016-01-01 03:15:00,177,
2016-01-01 03:30:00,203,
2016-01-01 03:45:00,170,
2016-01-01 04:00:00,174,
2016-01-01 04:15:00,165,
2016-01-01 04:30:00,182,
........
The first line is not useful. So I have to return 3 vectors, date, time, P_elec but I really have troubles writting the code for it. Does someone can help me with this please ?

채택된 답변

Star Strider
Star Strider 2018년 10월 14일
This will read your file:
fidi = fopen('Simon REMY B52-2016.txt');
D = textscan(fidi, '%{yyyy-MM-dd HH:mm:ss}D %f', 'HeaderLines',1, 'CollectOutput',1, 'Delimiter',',');
fclose(fidi);
datev = datetime(D{1}, 'Format','yyyy-MM-dd'); % Date Vector
timev = datetime(D{1}, 'Format','HH:mm:ss'); % Time Vector
P_elec = [D{2}]; % Power Vector
The ‘datev’ and ‘timev’ vectors are datetime (link) arrays. See the documentation to understand how to work with them. The ‘P_elec’ vector is a double array,m so you can work with it as is.
  댓글 수: 2
Simon REMY
Simon REMY 2018년 10월 15일
편집: Simon REMY 2018년 10월 15일
Thanks a lot for your help :) Your solution is simplier than what I was doing :p
Star Strider
Star Strider 2018년 10월 15일
As always, my pleasure!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by