【问题标题】:Extract information from path name从路径名中提取信息
【发布时间】:2020-06-15 23:14:42
【问题描述】:

我想在 MATLAB 中编写一个脚本,以某个名称保存我的输出数据。此名称的所有信息都在输入数据的路径中,如下所示:

path = 'C:\projektions100\algorithm1\method_A\data1';
projection = 
algorithm =
method =  
data = 

然后脚本应该从相邻的反斜杠中提取带有关键字(f.e. method)的路径中的文本,这样脚本就更加灵活,以防我在某些文件夹名称中出现拼写错误。 This is what I found to extract a text between a start and a end point 但我不能简单地使用反斜杠,因为路径中有一些反斜杠。 我应该如何进行?

【问题讨论】:

  • dir() 为您提供目录列表,包括路径名。然后您可以使用strsplit() 分隔字符串(在您的情况下为dir.folder),在字符串中使用反斜杠作为分隔符。然后您将所有文件夹名称放在单独的字符串中,因此您可以选择您需要的。
  • 谢谢!使用k = strfind(C,'argorithm') algorithm= C(find(~cellfun(@isempty,k)));,我还能够找到我的话
  • 太棒了!请注意,在 Stack Overflow 上发布您自己问题的答案是完全可以接受的,只要确保您遵守 How to Answer 中的规则即可。请这样做,因为这样可以让以后更容易找到这篇文章。

标签: matlab text-extraction


【解决方案1】:

您可以简单地使用带有命名令牌的regexp

>> path = 'C:\projektions100\algorithm1\method_A\data1';
>> all=regexp(path,'[^\\]+\\proje[ck]tion(?<projection>[^\\]+)\\algorithm(?<algorithm>[^\\]+)\\method(?<method>[^\\]+)\\data(?<data>.+$)','names')

all = 

  struct with fields:

    projection: 's100'
     algorithm: '1'
        method: '_A'
          data: '1'

【讨论】:

    【解决方案2】:

    问题在于如何找到关键字的结尾。这是一段代码,它循环遍历关键字并在路径中查找它们(存储在p2fldr中,因为变量path返回MATLAB中的工作路径,如果你定义它就会掩盖它)。

    p2fldr = 'C:\projektions100\algorithm1\method_A\data1';
    
    % keywords
    kyWrd = {'projection','algorithm','method','data'};
    Tag = cell(size(kyWrd));
    for i = 1:length(kyWrd)
        % get keyword
        ky = kyWrd{i};
        % look for it in the path
        idx = strfind(p2fldr,ky);
        if ~isempty(idx)
            % remaining path
            idx_offset = idx+strlength(ky);
            prm = p2fldr(idx_offset:end);
            % look for file separator '\'
            idx_tmp = strfind(prm,filesep);
            % if you don't find one, it is pabably the last entry, so take the
            % length
            if isempty(idx_tmp)
                idx_tmp = length(prm)+1;
            end
            % this is the index where it ends
            idx2 = idx_tmp(1)-1;
    
            % assign to tag-cell
            Tag{i} = prm(1:idx2);
        end
    end
    

    如果您知道它们始终位于路径的最后 4 个条目中,则可以构建快捷方式,因此您可以立即使用 strsplit 并索引最后返回的单元格

    str_splt = strsplit(p2fldr,filesep);
    Tag = cell(size(kyWrd));
    for i = 1:length(kyWrd)
        % index cells
        str = str_splt{end-length(kyWrd)+i};
        % get keyword
        ky = kyWrd{i};
        Tag{i} = str(length(ky)+1:end);
    end
    

    请注意,这并不关心它是否与您的关键字匹配(例如,您的路径显示'projektions',但我将关键字定义为'projection'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-14
      • 1970-01-01
      • 1970-01-01
      • 2010-10-01
      • 1970-01-01
      • 2016-06-19
      • 1970-01-01
      相关资源
      最近更新 更多