【问题标题】:MATLAB reads UNICODE CSV with spaces between charactersMATLAB 读取字符之间有空格的 UNICODE CSV
【发布时间】:2016-08-13 06:17:39
【问题描述】:

我正在使用fgetl 命令读取.csv 文件,但没有返回我想要的结果:

"HIST",1,1,27,PWH,"1"

它返回每个字符之间有额外的空格:

" H I S T         " , 1 , 1 , 2 7 , P W H , " 1 " 

我知道我可以用regexprep 替换空格,但我的文件包含数十亿行,因此添加的表达式可能会消耗更多时间。我有一种感觉,这是一个 unicode 问题,有人在他使用 Java 时指出了同样的问题,它与 unicode 有关。我想知道是否有人知道在 MATLAB 中处理该问题的更好方法?

更新:

这应该是 unicode 问题,因为 .csv 文件是另一个程序的输出,当我使用 fgetl 读取它时,会添加空格。但是,如果我再次使用 Excel 保存 .csv 文件并再次使用 fgetl 读取 .csv 文件,它会返回我想要的结果。

我无法提供示例,因为.csv 文件非常大,我无法制作小样本,因为当我从 Excel 打开并保存它时,这个问题就消失了。

【问题讨论】:

  • 请提供minimal reproducible example,在给定的示例中,我在 R2015b 中看不到这种行为。
  • 感谢您的评论!我相信这与“fgetl”的使用无关。这应该是 unicode 问题,因为 csv 文件是另一个程序的输出,当我使用 fgetl 读取它时,添加了空格。但是,如果我再次使用 excel 保存 csv 文件并再次使用 fgetl 读取 csv 文件,它会返回我想要的结果。很抱歉无法提供示例,因为csv文件太大,当我将它保存在excel中时,这个问题应该不会再存在了。
  • 为了创建一个示例,使用一些可以处理大文件的文本编辑器打开文件(我认为 Notepad++ 适合大多数应用程序,只需将前几行复制到一个单独的文件中)。 ..然后看看问题是否仍然存在,如果确实如此 - 将文件上传到某个地方供其他人测试。没有它,您的问题就无法真正重现,因此您将无法为您的问题找到特定的解决方案(而只能是一般的解决方案 - 就像我发布的那样)。

标签: matlab csv file-io unicode text-parsing


【解决方案1】:

出于演示的目的,让我们考虑一个演示文件 - demo.csv:

"GIST",1,6,17,PWH,"1"
"FIST",0,4,72,WPH,"2"
"MIST",3,2,27,WHP,"3"

你有一些选择:

  • textscan(对于任何具有已知结构的文本文件):

    fID = fopen('demo.csv');
    C = textscan(fID,'%s%d%d%d%s%s','Delimiter',{',','"'},'MultipleDelimsAsOne',1);
    fclose(fID);
    

    结果:

    C = 
    
    {3x1 cell}    [3x1 int32]    [3x1 int32]    [3x1 int32]    {3x1 cell}    {3x1 cell}
    
  • 导入助手 + 生成脚本(AKA 夸大其词):

结果:

%% Import data from text file.
% Script for importing data from the following text file:
%
%    F:\demo.csv
%
% To extend the code to different selected data or a different text file, generate a
% function instead of a script.

% Auto-generated by MATLAB on 2016/04/20 19:51:32

%% Initialize variables.
filename = 'F:\demo.csv';
delimiter = ',';

%% Read columns of data as strings:
% For more information, see the TEXTSCAN documentation.
formatSpec = '%q%q%q%q%q%q%[^\n\r]';

%% Open the text file.
fileID = fopen(filename,'r');

%% Read columns of data according to format string.
% This call is based on the structure of the file used to generate this code. If an error
% occurs for a different file, try regenerating the code from the Import Tool.
dataArray = textscan(fileID, formatSpec, 'Delimiter', delimiter,  '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=[2,3,4,6]
  % 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(numbers, 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


%% Split data into numeric and cell columns.
rawNumericColumns = raw(:, [2,3,4,6]);
rawCellColumns = raw(:, [1,5]);


%% Allocate imported array to column variable names
GIST = rawCellColumns(:, 1);
VarName2 = cell2mat(rawNumericColumns(:, 1));
VarName3 = cell2mat(rawNumericColumns(:, 2));
VarName4 = cell2mat(rawNumericColumns(:, 3));
PWH = rawCellColumns(:, 2);
VarName6 = cell2mat(rawNumericColumns(:, 4));


%% Clear temporary variables
clearvars filename delimiter formatSpec fileID dataArray ans raw col numericData rawData row regexstr result numbers invalidThousandsSeparator thousandsRegExp me rawNumericColumns rawCellColumns;
  • csvread(仅适用于数值;这意味着它不适用于此处)。

【讨论】:

  • 感谢开发者的演示!但我认为 textscan 不会节省我的时间,因为单元格 C 中的每个元素仍然包含空格
  • @Jackson 那么也许您应该预处理您的文件并使用e.g. regex..删除其中的所有空格?还要查看Whitespace 的可选输入textscan。顺便说一句,您可能想重新表述这个问题,因为在我看来,空格是您输入数据的属性,而不是“MATLAB 添加的”...
  • 再次感谢@Dev-iL。是的,regexprep 是我使用的。我正在运行这样的代码。:tline = fgetl(fid); str = regexprep(tline,a,''); temp = textscan(str,formatSpec,'Delimiter',','); 我只是想知道 MatLab 中是否有直接处理 UniCode 问题的函数....
【解决方案2】:

我碰巧遇到了同样的问题。我使用textscan 打开了一个.csv 文件,它在任何字符的两侧添加了1 个空格,我还注意到在打开存储读取数据的变量时,字体与Matlab 中的常用字体不同。

我们设法通过在 Notepad++ 中打开“.csv”文件并将编码更改为 UTF-8 来解决此问题。它解决了这个问题。

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 2015-03-27
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多