Hello, I have a text file that contains one column of words. I would like to read in the file as a string array of seperated strings so I can index the elements in the array.
Any advice is greatly appecraiated! Thanks!

댓글 수: 2

xRobot
xRobot 2019년 11월 19일
Using this, I obtained data as a 1x1 cell in the workspace.
fid = fopen('mylist2.txt');
data = textscan(fid,'%s');
fclose(fid);
Using this, I obtained words5 as a 1x111022 char array in the workspace.
fileID = fopen('mylist.odt','r');
formatSpec = '%s';
words5 = fscanf(fileID,formatSpec);
Ruger28
Ruger28 2019년 11월 19일
Please see my answer below to see how to use textscan and get strings

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

 채택된 답변

Ruger28
Ruger28 2019년 11월 19일

5 개 추천

fileName = '<your full file path here>'
% my sample text contains ---> apple, baseball, car, donut, & elephant in single column.
FID = fopen(fileName);
data = textscan(FID,'%s');
fclose(FID);
stringData = string(data{:});
Output:
stringData =
5×1 string array
"apple"
"baseball"
"car"
"donut"
"elephant"

댓글 수: 6

xRobot
xRobot 2019년 11월 19일
Your provided solution works great Ruger28. With that said, I am now tring to extract a random word from the string array using,
word = stringData(randi(numel(stringData)));
But I am getting "word" in the workspace as a string with many strange characters and combos of symbols.
It may be worth noting that my document is a .odt(open text document from MS) this was the only way to get it to stay in a column.
Ruger28
Ruger28 2019년 11월 19일
hmm..I am not sure about the .odt files. The snippet of code works fine for me and throws the words out randomly. Have you tried replacing "string" with "char"?
Ruger28
Ruger28 2019년 11월 19일
What version of MATLAB are you running?
xRobot
xRobot 2019년 11월 19일
R2019a
xRobot
xRobot 2019년 11월 19일
I got it! I just had to copy and paste the column into notepad as a regular .txt file. Thank you so much!
not a problem! try this just for fun.
odtFile = '<full filepath for file';
txtFile = fullfile(fileparts(odtFile),'TextVersion.txt');
copyfile(odtFile,txtFile);
fileName = txtFile;
...
...
<your script>
and then try runing your code. That way, you wont have to copy paste.

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

추가 답변 (0개)

카테고리

태그

질문:

2019년 11월 19일

댓글:

2019년 11월 19일

Community Treasure Hunt

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

Start Hunting!

Translated by