如何使用 `textscan` 将字符串转换为 table?

How to convert a string to a table with `textscan`?

我正在使用 matlab 使用 urlread 读取 COVID-19 data provided by Johns Hopkins as a .csv-file,但我不确定下一步如何使用 textscan 以便将字符串转换为一个table。 .csv 文件的前两列是指定区域的字符串,后面是大量包含按日期登记的感染数的列。

目前我只是将urlread返回的字符串保存在本地,然后用importdata打开这个文件,但肯定会有更优雅的解决方案。

您混淆了两件事:您想要使用“textscan”(当然还有“fopen”、“fclose”)从下载的 csv 文件中读取,或者您想要使用“urlread”(或者更确切地说是“webread”,因为 MATLAB 建议不要再使用“urlread”)。我选择后者,因为我自己从来没有这样做过^^

所以,首先我们读入数据并将其拆分成行

url = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv";
% read raw data as single character array
web = webread(url);
% split the array into a cell array representing each row of the table
row = strsplit(web,'\n');

然后我们分配一个table(预分配对MATLAB有好处,因为它将变量存储在RAM中的连续地址上,所以事先告诉MATLAB你需要多少space):

len = length(row);
% get the CSV-header as information about the number of columns
Head = strsplit(row{1},',');
% allocate table 
S = strings(len,2);
N = NaN(len,length(Head)-2);
T = [table(strings(len,1),strings(len,1),'VariableNames',Head(1:2)),...
    repmat(table(NaN(len,1)),1,length(Head)-2)];
% rename columns of table
T.Properties.VariableNames = Head;

请注意,我做了一个小技巧,通过重复单个 table 来分配这么多“NaN”的修复列。但是,将此 table 与字符串的 table 连接起来很困难,因为它们都包含列名 var1var2 .这就是为什么我立即重命名了第一个 table 的列。

现在我们可以实际填充 table(这有点讨厌,因为有人觉得把“韩国,南方”写成 逗号 很不错) -分隔文件)

for i = 2:len
    % split this row into columns
    col = strsplit(row{i},',');
    % quick conversion
    num = str2double(col);

    % keep strings where the result is NaN
    lg = isnan(num);
    str = cellfun(@string,col(lg)); 
    T{i,1} = str(1);
    T{i,2} = strjoin(str(2:end));% this is a nasty workaround necessary due to "Korea, South"
    T{i,3:end} = num(~lg);
end

这也适用于即将到来的日子。让我知道您实际上打算如何处理这些数据