【问题标题】:Import data from file delimited with various number of spaces从以不同数量的空格分隔的文件导入数据
【发布时间】:2014-10-09 04:46:09
【问题描述】:

我正在尝试将this 数据集读入一个元胞数组,但有两个问题

1) 分隔符是每列不同的空格

2) 第 4 列中有 6 个条目带有问号而不是数字

从文件中将这些数据读入元胞数组的好方法是什么?

【问题讨论】:

    标签: matlab file parsing import


    【解决方案1】:

    尝试以下方法:

    x = importdata('auto-mpg.data'); %// read lines
    y = cell(numel(x),9); %// preallocate with 9 cols (acccording to your file)
    for n = 1:numel(x)
        y(n,:) = regexp(x{n}, '(\s\s+)|\t', 'split'); %// split each line into 
        %// columns using as separator either more than one space or a tab
        %//(according to your file)
    end
    

    结果位于字符串y 的398x9 元胞数组中。

    【讨论】:

    • 感谢您的信息! importData 是否只是读取文档的每一行并将其作为垂直向量的一个元素(因此是字符串向量)?
    • 车名引号内的空格怎么办?
    • 什么意思?你没有在问题中提到这一点。是否也想根据这些空间拆分?去掉双引号?删除空格?
    • 我的意思是第 9 列的名称包含空格,我不想将包含 2 个单词的名称转换为两个不同的列。这会保留整个名称吗?
    • 我明白了,这行得通,现在我只需要将第 1-8 列转换为整数/浮点数。为什么正则表达式不使用空格分隔句子?
    【解决方案2】:

    下面是基于 MATLAB Import Tool 的代码:

    % Initialize variables.
    filename = '/home/gknor/Pulpit/auto-mpg.data';
    delimiter = {'\t',' '};
    
    % Read columns of data as strings:
    formatSpec = '%s%s%s%s%s%s%s%s%[^\n\r]';
    
    % Open the text file.
    fileID = fopen(filename,'r');
    
    % Read columns of data according to format string.
    dataArray = textscan(fileID, formatSpec, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true,  'ReturnOnError', false);
    
    % Close the text file.
    fclose(fileID);
    
    % Convert the contents of columns containing numeric strings to numbers.
    % Replace non-numeric strings with NaN.
    raw = repmat({''},length(dataArray{1}),length(dataArray)-1);
    for col=1:length(dataArray)-1
        raw(1:length(dataArray{col}),col) = dataArray{col};
    end
    numericData = NaN(size(dataArray{1},1),size(dataArray,2));
    
    for col=[1,2,3,4,5,6,7,8]
        % Converts strings in the input cell array to numbers. Replaced non-numeric
        % strings with NaN.
        rawData = dataArray{col};
        for row=1:size(rawData, 1);
            % Create a regular expression to detect and remove non-numeric prefixes and
            % suffixes.
            regexstr = '(?<prefix>.*?)(?<numbers>([-]*(\d+[\,]*)+[\.]{0,1}\d*[eEdD]{0,1}[-+]*\d*[i]{0,1})|([-]*(\d+[\,]*)*[\.]{1,1}\d+[eEdD]{0,1}[-+]*\d*[i]{0,1}))(?<suffix>.*)';
            try
                result = regexp(rawData{row}, regexstr, 'names');
                numbers = result.numbers;
    
                % Detected commas in non-thousand locations.
                invalidThousandsSeparator = false;
                if any(numbers==',');
                    thousandsRegExp = '^\d+?(\,\d{3})*\.{0,1}\d*$';
                    if isempty(regexp(thousandsRegExp, ',', 'once'));
                        numbers = NaN;
                        invalidThousandsSeparator = true;
                    end
                end
                % Convert numeric strings to numbers.
                if ~invalidThousandsSeparator;
                    numbers = textscan(strrep(numbers, ',', ''), '%f');
                    numericData(row, col) = numbers{1};
                    raw{row, col} = numbers{1};
                end
            catch me
            end
        end
    end
    
    % Replace non-numeric cells with NaN
    R = cellfun(@(x) ~isnumeric(x) && ~islogical(x),raw); % Find non-numeric cells
    raw(R) = {NaN}; % Replace non-numeric cells
    data = cat(2,raw,dataArray{9});
    
    % Clear temporary variables
    clearvars -except data
    

    有关导入工具的更多信息,您可以找到here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-12
      • 1970-01-01
      • 2018-11-02
      相关资源
      最近更新 更多