MATLAB:使用宽度分隔的 txt 文件进行文本扫描
MATLAB: textscan using width delimited txt file
我正在尝试使用 textscan
函数导入宽度分隔的 txt 文件。该文件为 80 个字符宽,没有分隔符,所需的 12 列是不同宽度的字符。我试图通过指定字符串的宽度来做到这一点,(即 12 个字符串,每个不同的字符宽度加起来为 80)但是一旦有 space(因为缺少某些值) MATLAB 将其解释为我的分隔符并弄乱了格式。
data= textscan(fileID, '%5s %7s %1s %1s %1s %17s %12s %12s %10s %5s %6s %3s');
我可以使用 Excel 来解决这个问题,但这似乎是一个糟糕的解决方案。有没有什么方法可以使用 MATLAB 来做到这一点,也许是与 textscan
/make textscan
忘记定界符而只处理字符串宽度的不同函数?
嗯,我在使用 textscan 时遇到了同样的问题。好吧,这里有很长的路要走(这绝不是最好的解决方案,但它应该有效)
fid=fopen('txtfile.txt','rt'); %//load in file
a=fscanf(fid'%c'); %//scan the thing into chars
fclose(fid);
for r = 0:NumberOfRowsInUrData -1 %//Now the loop... Number of rows in your data can also be calculated by size(a,2)/20
b(r+1,:) = a(1+20*r:20*(r+1)); %// this will correctly index everything
end
好消息是现在所有内容都在矩阵 b 中,您可以像 string1 = b(:,1:5) 一样简单地索引您的字符,它会在一个漂亮的矩阵中输出所有内容。
ofc 的缺点是 for 循环,我认为您应该可以用 cellfun 之类的东西替换它。
您需要将分隔符和白色 space 字符的值更改为空:
format_string = '%5s %7s %1s %1s %1s %17s %12s %12s %10s %5s %6s %3s';
C = textscan(fid, format_string, 'delimiter', '', 'whitespace', '');
这样 MATLAB 会将每个字符(包括 space )视为有效字符。
我正在尝试使用 textscan
函数导入宽度分隔的 txt 文件。该文件为 80 个字符宽,没有分隔符,所需的 12 列是不同宽度的字符。我试图通过指定字符串的宽度来做到这一点,(即 12 个字符串,每个不同的字符宽度加起来为 80)但是一旦有 space(因为缺少某些值) MATLAB 将其解释为我的分隔符并弄乱了格式。
data= textscan(fileID, '%5s %7s %1s %1s %1s %17s %12s %12s %10s %5s %6s %3s');
我可以使用 Excel 来解决这个问题,但这似乎是一个糟糕的解决方案。有没有什么方法可以使用 MATLAB 来做到这一点,也许是与 textscan
/make textscan
忘记定界符而只处理字符串宽度的不同函数?
嗯,我在使用 textscan 时遇到了同样的问题。好吧,这里有很长的路要走(这绝不是最好的解决方案,但它应该有效)
fid=fopen('txtfile.txt','rt'); %//load in file
a=fscanf(fid'%c'); %//scan the thing into chars
fclose(fid);
for r = 0:NumberOfRowsInUrData -1 %//Now the loop... Number of rows in your data can also be calculated by size(a,2)/20
b(r+1,:) = a(1+20*r:20*(r+1)); %// this will correctly index everything
end
好消息是现在所有内容都在矩阵 b 中,您可以像 string1 = b(:,1:5) 一样简单地索引您的字符,它会在一个漂亮的矩阵中输出所有内容。
ofc 的缺点是 for 循环,我认为您应该可以用 cellfun 之类的东西替换它。
您需要将分隔符和白色 space 字符的值更改为空:
format_string = '%5s %7s %1s %1s %1s %17s %12s %12s %10s %5s %6s %3s';
C = textscan(fid, format_string, 'delimiter', '', 'whitespace', '');
这样 MATLAB 会将每个字符(包括 space )视为有效字符。