我想计数文本文件中仅以特定字符串开头的字符串数。
function count = countLines(fname)
fh = fopen(fname, 'rt');
assert(fh ~= -1, 'Could not read: %s', fname);
x = onCleanup(@() fclose(fh));
count = 0;
while ~feof(fh)
count = count + sum( fread( fh, 16384, 'char' ) == char(10) );
end
count = count+1;
end我使用上面的函数来计算整个.text文件中的行数。但是现在我想找出以特定字符串开头的行数(例如。所有以字母‘s’开头的行)。
发布于 2014-09-26 10:40:09
您可以在这里尝试两种基于importdata的方法。
方法#1
str1 = 's'; %// search string
%// Read in text data into a cell array with each cell holding text data from
%// each line of text file
textdata = importdata(fname,'\n') ;
%// Compare each cell's starting n characters for the search string, where
%// n is no. of chars in search string and sum those matches for the final count
count = sum(cellfun(@(x) strncmp(x,str1,numel(str1)),textdata)) 方法#2
%// ..... Get str1 and textdata as shown in Approach #1
%// Convert cell array data into char array
char_textdata = char(textdata)
%// Select the first n columns from char array and compare against search
%// string for all characters match and sum those matches for the final count.
%// Here n is the number of characters in search string
count = sum(all(bsxfun(@eq,char_textdata(:,1:numel(str1)),str1),2))使用这两种方法,您甚至可以将char数组指定为搜索字符串。
发布于 2014-09-26 09:08:39
虽然我不理解您的代码背后的想法,所以我不能修改它,我使用了以下方法:
fid = fopen(txt);
% Loop through data file until we get a -1 indicating EOF
while(x ~= (-1))
line = fgetl(fid);
r = r+1;
end
r = r-1;r是文件中的行数。在增加计数器line以满足您的条件之前,您可以轻松地检查r的值。
另外,我不知道这两种方法的性能问题是什么。
https://stackoverflow.com/questions/26055507
复制相似问题