2017-01-03 81 views
-4

我需要在matlab中編寫一個程序來搜索文本文件中的特定關鍵詞,然後在文本中計算這個特定詞的數量。如何使用matlab搜索文本文件以計算特定的單詞?

+4

我投票結束這個問題作爲題外話,因爲它表明沒有努力,可能只是一個做我的作業類型的問題。請修改以顯示您嘗試過的內容以及*特定*不起作用的內容。 – gnovice

回答

1

首先看看如何用Matlab讀取文本文件,然後使用textscan函數,它是讀取整個數據到單元陣列Matlab中的內置函數,並使用strcmp將數組中的每個元素與特定關鍵字進行比較。

我提供了一個函數,它將文件名和關鍵字作爲輸入並輸出文件中存在的關鍵字的計數。

function count = count_word(filename, word) 
count = 0;     %count of number of specific words 
fid = fopen(filename);  %open the file 
c = textscan(fid, '%s'); %reads data from the file into cell array c{1} 

for i = 1:length(c{1}) 
    each_word = char(c{1}(i)); %each word in the cell array 
    each_word = strrep(each_word, '.', ''); %remove "." if it exixts in the word 
    each_word = strrep(each_word, ',', ''); %remove "," if it exixts in the word 

    if (strcmp(each_word,word)) %after removing comma and period (if present) from each word check if the word matches your specified word 
     count = count + 1;  %increase the word count 
    end 
end 
end 
0

Matlab實際上有一個功能strfind它可以爲你做到這一點。查看Mathworks doc瞭解更多詳情。

的文本文件的內容應該被存儲在一個變量:

text = fileread('filename.txt') 
相關問題