2014-03-26 54 views
0

我有一個非常大的文本文件,我試圖對其進行文字分析。在字數統計中,我可能也在尋找其他信息,但爲了簡單起見,我將其留下了。 在這個文本文件中,我有以星號「*」分隔的文本塊。我下面的代碼掃描了文本文件,並按照它應該打印的字符和單詞#,但是我希望在滿足星號後重置計數器,並將所有信息存儲在某種表格中。我並不擔心我如何製作表格,因爲我不確定如何在星號之間爲每個文本塊循環相同的計數代碼。C重置FOR循環中的數據計數器

也許一個for循環像

for (arr = strstr(arr, "*"); arr; arr = strstr(arr + strlen("*"), "*")) 

示例文本文件:

=-=-=-=-=-=-=-=-=-=-=-=-=-=- 
I have a sentence. I have two sentences now. 
* 
I have another sentence. And another. 
* 
I'd like to count the amount of words and characters from the asterisk above this 
one until the next asterkisk, not including the count from the last one. 
* 
... 
    ... 
    -=-=-=-=-=-=-=-=-=-=-=-=-=-=- 
    (EOF) 

Desired output: 

    *#  #words  #alphaChar 
    ---------------------------- 
    1  9   34 
    ----------------------------- 
    2  5   30 
    ----------------------------- 
    3  28   124 
    ... 
    ... 


I have tried 

     #include <stdio.h> 
     #include <stdlib.h> 
     #include <string.h> 

     int main() 
      { 
      int characterCount=0; 
      int counterPosition, wordCount=0, alphaCount=0; 

      //input file 
      FILE *file= fopen("test.txt", "r"); 
      if (file== NULL) 
      printf("Cannot find the file.\n"); 


      //Count total number of characters in file 
      while (1) 
       { 
       counterPosition = fgetc(speechFile); 
       if (counterPosition == EOF) 
       break; 
       ++characterCount; 
       } 

      rewind(file); // Sends the pointer to the beginning of the file 

      //Dynamically allocate since array size cant be variable 
      char *arr= (char*) malloc(totalCharacterCount); 

      while(fscanf(speechFile, "%c", &arr[i]) != EOF) //Scan until the end of file. 
      i++; //increment, storing each character in a unique position 



       for(i = 0; i <characterCount; i++) 
        { 
        if(arr[i] == ' ') //count words 
        wordCount++; 

        if(isalpha(arr[i])) //count letters only 
        alphaCount++; 

        }//end for loop 

       printf("word count is %d and alpha count is %d", wordCount,alphaCount); 
      } 
+0

wordcount和alphacount未初始化。你也可以在每個空間增加wordcount,所以「」(2個空格)可以算作兩個單詞。和'char * arr =(char *)malloc(totalCharacterCount * sizeof(int));'可以是'char * arr = malloc(totalCharacterCount);' – wildplasser

+0

已添加修正。但這不是問題。我重寫了大部分代碼,而不是複製和粘貼,所以初始化會滑掉我的想法。 – user3465668

+0

當只需要一次傳遞時,爲什麼程序會進行三次傳遞(兩次用於文件,一次用於數組)。另外:該計劃似乎與你的目標幾乎沒有關係。 – wildplasser

回答

0

由於您有在陣列全文件中的文本改編[],你需要劃分使用*作爲字符串arr分隔符。您可以使用strtok()*作爲分隔符來劃分該字符串。然後對每個令牌執行字數和字符計數操作。閱讀此鏈接瞭解strtok

+0

我記得有人在另一篇文章中提到strtok,但由於某種原因,我認爲這是無關緊要的。你說的話有道理,我會試試看。謝謝! – user3465668

+0

@ user3465668 ok。亞有問題討論在堆棧中使用strtok(),所以我dint去添加代碼。閱讀其中之一。檢查[this](http://stackoverflow.com/questions/8106765/using-strtok-in-c)知道如何使用strtok。它可以幫助你編碼 – LearningC