gpt4 book ai didi

python - Matlab 相当于 `endsWith` : How to filter list of filenames regarding their extension?

转载 作者:太空宇宙 更新时间:2023-11-04 10:24:34 25 4
gpt4 key购买 nike

在 Python、Java 等中是否有与 endswith 函数等效的 MATLAB 函数?

我想按结尾过滤字符串列表,例如列表:

a.tif
b.jpg
c.doc
d.txt
e.tif

应由 endswith('.tif') 过滤以产生:

a.tif
e.tif

下面是我在 Python 中的做法:

textList = ['a.tif','b.jpg','c.doc','d.txt','e.tif'];
filteredList = filter(lambda x:x.endswith('.tif'), textList)

这是我在 MATLAB 中尝试的:

textList = {'a.tif'; 'b.jpg'; 'c.doc'; 'd.txt'; 'e.tif'};
found = strfind(textList, '.tif');
a = zeros(size(found)); for k = 1:size(found), a(k)=~isempty(found{k}); end;
textList(logical(a))

我可能必须将 strfind 替换为 regexp 才能找到字符串末尾的匹配项。总的来说,我认为这是实现目标的一种相当复杂的方式。有没有更简单的方法在 MATLAB 中过滤列表?

最佳答案

可能非常有效的方法是使用正则表达式:

filelist = {'a.tif'
'c.doc'
'd.txt'
'e.tif'}

filtered = regexp( filelist ,'(\w*.txt$)|(\w*.doc$)','match')
filtered = [filtered{:}]

解释:

(\w*.txt$)将返回所有文件名 \w*哪一端$.txt(\w*.doc$)将返回所有文件名 \w*哪一端$.doc . |只是逻辑运算符。

特别是如果你只想过滤一个文件扩展名,它真的很方便:

fileExt = 'tif';
filtered = regexp( filelist ,['\w*.' fileExt '$'],'match')
filtered = [filtered{:}]

过滤多个文件扩展名也是可以的,但是你需要创建一个更长的regex:

fileExt = {'doc','txt'};
dupe = @(x) repmat({x},1,numel(fileExt))
filter = [dupe('(\w*.'); fileExt(:).'; dupe('$)'); dupe('|')] %'

filtered = regexp( filelist, [filter{1:end-1}], 'match')
filtered = [filtered{:}]

关于python - Matlab 相当于 `endsWith` : How to filter list of filenames regarding their extension?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30121541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com