不打印整行,只打印C中的块?

时间:2016-06-02 22:28:05

标签: c linked-list

我很难将文件中的输入添加到结构中。我想从一个由path指定的文本文件中读入,将每行添加到一个新的char *命名引号,并将引号添加到名为Thread的结构中,该结构使用名为table的链表进行初始化。

当我向表中添加一个单词时,我将其添加为链接列表。这可能是我的困难所在,但我看不出如何解决它。

诀窍是我可以看到从char *引用打印出的整个报价。在我将它添加到结构中之后,然后尝试通过引用t->quotes[i]->quote的结构来打印它,它只打印一个单词。

 Thread* initialize_thread(char* path, Classifier *clf, int size){
   Thread* t = malloc(sizeof(t) * size);
   t->clf = clf;
   FILE *fp = fopen(path, "r");
   t->size = 0;

   char line[300]; /* 300 is an arbitrary length to read in lines from the text file*/
   int count = 0;
   if(fp == NULL){
      perror("Error opening file");
      return NULL;
   }
   if ((t->table = malloc(sizeof(t->table) * size)) == NULL){
    return NULL;
   }
   for (int i = 0; i < size; i++) {
       t->table[i] = NULL;
   }

   while (fgets(line, 300, fp)){
      char* quote = strdup(line);


      LinkedTest* new = malloc(sizeof(*new));
      new->quote = quote;

      printf("%s\n", new->quote);
      float c = get_score(t->clf, quote);
      new->score = c;
      t->table[count] = new;
      count ++;

      printf("%s\n", new->quote);

   }
   t->size = count;
   return t;
}

头文件在这里:

typedef struct LinkedTest {
    float score;
    char* quote;
    struct LinkedList *next;
} LinkedTest;

typedef struct Thread {
    LinkedTest** table;
    Classifier *clf;
    int size;
} Thread;

Thread* initialize_thread(char* path, Classifier *clf, int size);

void write_quotes(char* path, Thread* t);

#endif /* READ_H*/

get_score()就在这里:

float get_score(Classifier* clf, char* fragment){
    int l = strlen(fragment);
    char* grams[l];
    for (int i = 0; i < l; i++){
         grams[i] = NULL;
    }

    // this function makes a call to strtok()
    int set = get_grams(fragment, grams);

    int length = 0;
    float score = 0.0;

    // for every gram, get a score
    for (int i = 0; i < l; i++){
        char* g = grams[i];

        if (g != NULL){
            float num = 1.0;
            float denom = set;
            length++;

            float gp = get_gram_probability(clf->dictionary, g);
            float pp = get_probability_gram_is_positive(clf->dictionary, g);

            // numerator = 1 + prob_gram_positive * class_prob
            float p = clf->class_prob;
            num += (pp * p);

            // denominator = length of the input string + gram_prob
            denom += gp;

            score += num / denom;
        }   
    }

return score / length;
}

这是get_grams()。它需要将一个克[]初始化为给定的长度和一个句子,并用句子中的单词填充克。

int get_grams(char* sentences, char* grams[]){
    // Is given an empty char* grams, populates it with words from the sentence
    int count = 0;
    char* words = strtok(sentences, " ");
    while (words != NULL){
        grams[count] = words;
        words = strtok(NULL, " ");
        count ++;
    }
    return count;
} 

0 个答案:

没有答案