How to read UTF-8 txt file by using MATLAB

9 次查看(过去 30 天)
[EDIT: 20110614 23:00 CDT - reformat - WDR]
I am a newer to learn Matlab, and I want to know how to load the text file into matrix.
I have a text file in form of .txt. The text is telling about a maze map.
In the text below Unicode code points are indicated in parentheses. Maze walls are indicated by "█" (U+2588). Free space is indicated by " " (U+0020). The Robot's starting point is indicated by "S" (U+0053) and the goal is indicated by "G" (U+0047).
█████████
S █ █
█ ███ █ █
█ █ █
███ ███ █
█ ███ ███
G
█████████
In this case, how can I read the files like this.
I had tried fopen/textread. but it cannot load it.
Thank you very much for your helping.

回答(3 个)

Fangjun Jiang
Fangjun Jiang 2011-6-15
Supposedly, fopen() can read unicode text file if the text file is saved with UTF-8 encoding, e.g. fid=fopen('test.txt','r','n','UTF-8'). But in your case, I think as long as you can distinguish those different characters, you can then process it for whatever you need. Assume the test.txt file contains the line shown in your question, the following lines can read it.
fid=fopen('test.txt','rt');
Maze=[];
while ~feof(fid)
Line=fgetl(fid);
Maze=[Maze;Line];
end
fclose(fid);
Maze
isspace(Maze)
[Xs,Ys]=find(Maze=='S')
[Xg,Yg]=find(Maze=='G')
Maze =
?????????
?S ? ?
? ??? ? ?
? ? ? ?
??? ??? ?
? ? ?
? ??? ???
? G?
?????????
ans =
0 0 0 0 0 0 0 0 0
0 0 1 1 1 1 0 1 0
0 1 0 0 0 1 0 1 0
0 1 0 1 0 1 1 1 0
0 0 0 1 0 0 0 1 0
0 1 1 1 0 1 1 1 0
0 1 0 0 0 1 0 0 0
0 1 1 1 1 1 1 0 0
0 0 0 0 0 0 0 0 0
Xs =
2
Ys =
2
Xg =
8
Yg =
8

Walter Roberson
Walter Roberson 2011-6-15
See the hints in this previous Question

MathWorks Support Team
编辑:MathWorks Support Team 2021-2-19
As of R2020a, the MATLAB Editor and other functions like type, fopen, and fileread automatically determine the current encoding when opening existing files.

类别

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