read file containing mixed content

1 次查看(过去 30 天)
Hello,
The format of an input text file is the following:
1 23.08 был
2 367.92 сказал
3 12567.53 когда
...
and so on.
How to read this file so that the following loop can be used:
for i=1:length(file)
str=fileName(i,3);
...
end
Thanks.
  9 个评论
Christopher Creutzig
20a may need a hint as to the file encoding you are using. readtable("a.txt","Encoding","UTF-8","NumHeaderLines",0) seems to work for me.
b
b 2022-1-12
Thank you. Thats exactly where the problem was.

请先登录,再进行评论。

采纳的回答

Image Analyst
Image Analyst 2022-1-8
Try this:
% Get file name
fullFileName = fullfile(pwd, 'a.txt')
if ~isfile(fullFileName)
errorMessage = sprintf('Error: file not found:\n%s', fullFileName);
fprintf('%s\n', errorMessage)
uiwait(errordlg(errorMessage))
return;
end
% Open the file for reading in text mode.
fileID = fopen(fullFileName, 'rt');
% Read the first line of the file.
textLine = fgetl(fileID);
lineCounter = 1;
while ischar(textLine)
% Print out what line we're operating on.
fprintf('%s\n', textLine);
% Split into words.
words = strsplit(textLine);
% Assign to vectors
col1(lineCounter) = str2double(words{1});
col2(lineCounter) = str2double(words{2});
col3{lineCounter} = words{3};
% Read the next line.
textLine = fgetl(fileID);
lineCounter = lineCounter + 1;
end
% All done reading all lines, so close the file.
fclose(fileID);
% Transpose from row vectors into column vectors
col1 = col1'
col2 = col2'
col3 = col3'
  3 个评论
Image Analyst
Image Analyst 2022-1-9
It worked for me with my copy and paste of your original post. If it's not working with your original file, please attach your data file so I can check my program with your actual data file.
b
b 2022-1-10
Hmmm ... oddly and strangely, it is somehow working now ...

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 String Parsing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by