2015-06-21 105 views
2

我需要與上字母輸入句子,然後拆分句子的單詞和字符的每一個字計數「一」拆分句子的單詞和計數的字符數「A」中的每個字

我VE使這個

clear 
sentences=input('Write your sentences: ','s'); 
low=lower(sentences); 
disp('Sentences splitted to words: '); 
words=regexp(low,' ','split'); 
for i=1:length(words) 
    disp(words(i)) 
end 

現在我不知道如何計算每個分割後的單詞「一」字,因爲這些詞被轉換成細胞。 有人可以幫助我嗎?

+0

從這裏開始:

count = cellfun(@(w) sum(w=='a'), words); 

您可以同樣使用一個循環文檔:[字符和字符串](http://www.mathworks.com/help/matlab/characters-and-strings.html) – horchler

+0

沒有必要在標題中人爲插入標籤;理想情況下,標題應該是連貫的句子 – 2015-06-24 20:11:04

回答

0

處理每個單元格,使用cellfunanonymous function計數'a'發生在每個單詞的次數:在

N = numel(words); 
count = NaN(1,N); %// preallocate for speed 
for n = 1:N 
    w = words{n}; 
    count(n) = sum(w=='a'); 
end 
+0

'w =='a''對於字符串來說通常是不好的做法(除非一個字符串執行一組輸入驗證)。 'strfind'可能是更好的選擇:'count = cellfun('length',strfind(words,'a'))''。 – horchler

+0

使用'=='測試兩個字符串是否是不好的做法(它們可能有不同的長度),但我認爲將字符串與_character_進行比較並不是一個壞習慣。或者我錯過了什麼? –

相關問題