我走近問題的方式如下:
function ok = lets(file_name)
file = memmapfile(file_name, 'writable', false);
lowercase = [65:90];
uppercase = [97:122];
data = file.Data;
ok = sum(histc(data,lowercase)+histc(data,uppercase));
end
我映射文件使用memmapfile
函數存儲器,並與所述字符編碼數據從this ASCII table。小寫字母由[65:90]
和大寫字母[97:122]
表示。通過應用histc函數,我得到了每個字母出現在文件中的頻率。通過將所有頻率加起來給出字母的總數。
請注意,我調用了histc
兩次以避免從90
到97
的bin會計入[]^_`個字符。
我施加的函數稱爲樣品文件sample.txt包含以下行:
abc23D&f![
k154&¨&skj
djaljaljds
這是我的輸出:
>> lets('sample.txt')
Elapsed time is 0.017783 seconds.
ans =
19
編輯:
輸出ok=-1
讀取文件時出現問題:
function ok = lets(fclose(fid);file_name)
try
file = memmapfile(file_name, 'writable', false);
catch
file=[];
ok=-1;
end
if ~isempty(file)
lowercase = [65:90];
uppercase = [97:122];
data = file.Data;
ok = sum(histc(data,lowercase)+histc(data,uppercase));
end
end
隨着fopen
的方法,因爲你得到的ok=-1
「默認」:
function ok = lets(file_name)
fid = fopen(file_name, 'rt');
if fid < 0
ok = -1;
else
celldata=textscan(fid,'%s');
fclose(fid);
lowercase = [65:90];
uppercase = [97:122];
data = uint8([celldata{1}{:});
ok = sum(histc(data,lowercase)+histc(data,uppercase));
end
end
你可以發佈一個小樣本文件和預期產出? –