How to read in a text file with data seperated by a colon first, than a comma and than a dash?
5 次查看(过去 30 天)
显示 更早的评论
Hello,
I have a .txt file with thousands of lines of data that I want to read into my Matlab workspace. The problem is that the data does not use a consistent separation. For example, 2 lines of data look similar to this:
HA: 2012-01-08, 11:01:45.802 – FFFF0811111111210208
BA: 2012-01-08, 11:01:45.805 – FFFF0811111111220333
In this, I have a variable, “HA” and “BA”, each with a date, time and 422 data. I want to read in this data for a large number of lines. I am trying textscan but I am a little confused how to read in the data because it is not separated by a consistent delimiter such as comma-delimited. Thus far, I have wrote:
fid=fopen('TheData.txt','r');
TextData=textscan(fid,'%s');
I am trying to get my script into a format similar to what Matlab shows in "help textscan":
“C = textscan(FID,'FORMAT',N,'PARAM',VALUE)”
Any help is greatly appreciated.
Thank you.
0 个评论
采纳的回答
Dan K
2013-3-8
Here's a place to start from:
str1 = 'HA: 2012-01-08, 11:01:45.802 – FFFF0811111111210208'
C = textscan(str1,'%2c:%d-%d-%d, %d:%d:%f%[^- ]%s')
What this does is:
1. Read 2 characters
2. Then read three integers separated by hypens
3. Then read two integers and a floating point separated by colons
4. Capture or throw away the hypen
5. Then capture the (I assume hex) string at the end.
Hope this helps.
0 个评论
更多回答(1 个)
Jason Ross
2013-3-8
编辑:Jason Ross
2013-3-8
I'd suggest taking the example you have there, putting it in a file, and using the Import Wizard. In the upper left hand side, you can select "Delimiter" and enter the delimiters you want to use, and preview your data. Under "Import Selection", you can select "generate function" or "generate script", and in that generated file will be the textscan code to use.
Note that you might need to get the delimiters right first, then combine the data back in a separate operation.
Alternatively you might want to look at using regular expresssions, but that might be more hassle than doing the import and then combining things as you want to.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Import and Export 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!