2015-05-26 35 views
0

我試圖計算文本文件中的字母數,但不幸的是,如果涉及數字,我會一直卡住。閱讀文本文件和處理數字

到目前爲止,我已經能夠處理字母和符號,但不幸的是,當涉及到數字時,ischar函數並沒有幫助我。

function ok = lets(file_name) 
fid = fopen(file_name, 'rt'); 
if fid < 0 
    ok = -1; 
end 
C = []; 
D = []; 
oneline = fgets(fid); 

while ischar(oneline) 
    C = oneline(isletter(oneline)); 
    W = length(C); 
    D = [D ; W]; 
    oneline = fgets(fid); 
end 
total = 0; 
for i = 1:length(D) 
    total = D(i) + total; 
end 
ok = total; 

如何處理計數字母,如果在文本文件中還有數字?

+0

你可以發佈一個小樣本文件和預期產出? –

回答

1

我走近問題的方式如下:

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兩次以避免從9097的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 
+0

如果在打開文件時出現問題,我希望輸出爲-1,我將如何修改此函數? – statsguyz

+0

我會把它包裝在try catch語句中。如果打開文件時遇到問題,您可以分配ok = -1。如果我使用fread,同樣的想法也適用。否則,我會使用fopen來打開文件,因爲你需要-1這是fopen的標準。檢查我的編輯 – brodoll

+0

@statsguyz它如何爲你工作? – brodoll

1

我認爲你使這個比它需要的更復雜,就像你使用isletter然後使用length

function ok = lets(file_name) 
%Original code as you had it 
fid = fopen(file_name, 'rt'); 
if fid < 0 
    ok = -1; 
end 
%Initialize length 
ok = 0; 
%Get first line 
oneline = fgets(fid); 

%While line isn't empty 
while oneline ~= -1 
    %remove everythin that's not a letter 
    oneline(~isletter(oneline)) = []; 
    %Add number of letters to output 
    ok = ok + length(oneline); 
    %Get next line 
    oneline = fgets(fid); 
end 
end 

我使用的輸入文件,

Ar,TF,760,2.5e-07,1273.14,4.785688323049946e+24,24.80738364864047,37272905351.7263,37933372595.0276 
Ar,TF,760,5e-07,1273.14,4.785688323049946e+24,40.3092219226107,2791140681.70926,2978668073.513113 
Ar,TF,760,7.5e-07,1273.14,4.785688323049946e+24,54.80989010679312,738684259.1671219,836079550.0157251 

,並得到18,這種計數e的的數字,你想這些要算?