2014-02-28 21 views
0

對於任務,我需要找到文本文件的句子數(而不是行數)。這意味着在字符串末尾我會有'。'要麼 '!'要麼 '?'。在掙扎了很多之後,我寫了一個代碼,這是一個錯誤。我沒有看到任何錯誤。如果任何人都可以幫助我,那將是高度讚賞。由於計算句子*不是*文本文件的行

這裏是我的代碼

fh1 = fopen(nameEssay); %nameEssay is a string of the name of the file with .txt 
line1 = fgetl(fh1); 

%的LINE-1給出了文章的標題。即不算作句子

essay = []; 
line = ' '; 
while ischar(line) 
    line =fgetl(fh1); 
    essay = [essay line]; 
    %creates a long string of the whole essay 
end 

sentenceCount=0; 
allScore = [ ]; 



[sentence essay] = strtok(essay, '.?!'); 
while ~isempty(sentence) 
    sentenceCount = sentenceCount + 1; 
    sentence = [sentence essay(1)]; 

    essay= essay(3:end); %(1st character is a punctuation. 2nd is a space.) 
    while ~isempty(essay) 
     [sentence essay] = strtok(essay, '.?!'); 
    end 

end 
fclose(fh1); 
+1

什麼錯誤和哪一行? – Marcin

+1

而不是'strtok',你應該看看['strsplit''](http://www.mathworks.com/help/matlab/ref/strsplit.html),然後你可以計算單元格的長度它返回的矩陣。 – Dan

+0

在計算兩個句子之後,這裏給出錯誤 「句子= [句子短文(1)]」numeri(essay)= 0。 但是,我沒有看到原因! – user3226108

回答

3

regexp處理這個問題很好:

>> essay = 'First sentence. Second one? Third! Last one.' 
essay = 
First sentence. Second one? Third! Last one. 
>> sentences = regexp(essay,'\S.*?[\.\!\?]','match') 
sentences = 
    'First sentence.' 'Second one?' 'Third!' 'Last one.' 

在模式'\S.*?[\.\!\?]',該\S說,一個句子以非空白字符開始時,.*?匹配任何數目的字符(非貪婪)的,直到一個標點符號標記句子結尾([\.\!\?])遇到。

+0

它看起來像一個不錯的命令。但是,我們還沒有被教導!雖然謝謝! – user3226108

3

如果您計算的句數,基於'。'要麼 '!'或'?',你可以在essey中計算這些字符的數量。因此,如果作文是包含字符數組,你可以這樣做:

essay = 'Some sentece. Sentec 2! Sentece 3? Sentece 4.'; 


% count number of '.' or '!' or '?' in essey. 
sum(essay == abs('.')) 
sum(essay == abs('?')) 
sum(essay == abs('!')) 

% gives, 2, 1, 1. Thus there are 4 sentences in the example. 

如果你想senteces,你可以使用strsplit丹建議,例如

[C, matches] = strsplit(essay,{'.','?', '!'}, 'CollapseDelimiters',true) 

% gives 
C = 

    'Some sentece' ' Sentec 2' ' Sentece 3' ' Sentece 4' '' 


matches = 

    '.' '!' '?' '.' 

並計算匹配中的元素數量。例如,最後一個元素是空的。它可以很容易地過濾出來。

+0

是......的確如此。但是,我還需要實際的句子,來完成整個功能的另一個任務!因此,我需要兩個。抱歉。我應該提到這一點。謝謝! – user3226108

+0

@ user3226108我修改了anwser – Marcin

+0

我認爲strsplit()是一個新的命令。我正在使用2011版本。沒有這樣的命令。即使我有,這對於這項任務也是有用的(據我所知)。因爲它消除了句子中的標點符號。我需要一個完整的句子。感謝您的嘗試! – user3226108