2014-09-26 57 views
2

我想算串的數量在一個文本文件開始時只計數開始與特定字符串的行數 - Matlab的

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文件中的行。但是現在我想查找以特定字符串開頭的行數(例如,所有以字母開始的行)。

回答

0

您可以在這裏嘗試兩種方式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)) 

有了這兩種方法,你甚至可以指定一個字符數組作爲搜索字符串。

0

雖然我沒有得到你的代碼背後的想法,所以我不能改變它,我用這個辦法:

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是文件中的行數。您可以在增加計數器r之前輕鬆檢查line的值,以便首先滿足您的條件。

另外我不知道這兩種方法的性能問題是什麼。

相關問題