Read in Text File as string Array

115 ビュー (過去 30 日間)
xRobot
xRobot 2019 年 11 月 19 日
コメント済み: Ruger28 2019 年 11 月 19 日
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 日
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 日
I got it! I just had to copy and paste the column into notepad as a regular .txt file. Thank you so much!
Ruger28
Ruger28 2019 年 11 月 19 日
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 件)

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by