Matlab相当于"endsWith":如何过滤有关扩展名的文件名列表? [英] Matlab equivalent of `endsWith`: How to filter list of filenames regarding their extension?
问题描述
是否存在与endswith
函数等效的MATLAB,该函数可以在Python,Java等中使用?
Is there a MATLAB equivalent of the endswith
function available in Python, Java etc.?
我想按字符串的结尾过滤字符串列表,例如列表:
I would like to filter a list of Strings by their endings, e.g. the list:
a.tif
b.jpg
c.doc
d.txt
e.tif
应使用endwith('.tif')进行过滤以得出:
should be filtered by endswith('.tif') to result in:
a.tif
e.tif
这是我要在Python中执行的操作:
Here's how I would do it in Python:
textList = ['a.tif','b.jpg','c.doc','d.txt','e.tif'];
filteredList = filter(lambda x:x.endswith('.tif'), textList)
这是我在MATLAB中尝试过的:
This is what I tried in 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))
我可能不得不用regexp
替换strfind
来查找字符串末尾的出现.总的来说,我认为这是实现目标的一种相当复杂的方法.
有没有一种简便的方法可以在MATLAB中过滤列表?
I might have to replace strfind
by regexp
to find occurences at the end of the string. In general, I think this is a rather complicated way of achieving the goal.
Is there an easier way to filter the list in MATLAB?
推荐答案
使用正则表达式可能非常有效:
Probably quite efficient is to use regular expressions:
filelist = {'a.tif'
'c.doc'
'd.txt'
'e.tif'}
filtered = regexp( filelist ,'(\w*.txt$)|(\w*.doc$)','match')
filtered = [filtered{:}]
说明:
(\w*.txt$)
将返回以.txt
结尾的所有文件名\w*
,而(\w*.doc$)
将返回以.doc
结尾的所有文件名\w*
. |
只是逻辑运算符.
(\w*.txt$)
will return all filenames \w*
which end $
with .txt
and (\w*.doc$)
will return all filenames \w*
which end $
with .doc
. The |
is just the logical operator.
特别是如果您只想过滤一个文件扩展名,那真的很方便:
Especially if you just want to filter for one file extension, it is really handy:
fileExt = 'tif';
filtered = regexp( filelist ,['\w*.' fileExt '$'],'match')
filtered = [filtered{:}]
也可以过滤多个文件扩展名,但是您需要创建更长的 regex :
Filtering multiple file extensions is also possible, but you need to create a longer 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{:}]
这篇关于Matlab相当于"endsWith":如何过滤有关扩展名的文件名列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!