1

我正在读取具有以下格式的文件:

    /* ...more text above */
    [Text=WORKING CharacterOffsetBegin=73516 CharacterOffsetEnd=73523 PartOfSpeech=VBG                 
    Lemma=work] [Text=MEN CharacterOffsetBegin=73524 CharacterOffsetEnd=73527                    
    PartOfSpeech=NNS Lemma=man] [Text=OF CharacterOffsetBegin=73528
    CharacterOffsetEnd=73530 PartOfSpeech=IN Lemma=of] [Text=ALL
    CharacterOffsetBegin=73531 CharacterOffsetEnd=73534 PartOfSpeech=NN Lemma=all] 
    [Text=COUNTRIES CharacterOffsetBegin=73535 CharacterOffsetEnd=73544 PartOfSpeech=NNS 
    Lemma=country] [Text=, CharacterOffsetBegin=73544 CharacterOffsetEnd=73545
    PartOfSpeech=, Lemma=,] [Text=UNITE CharacterOffsetBegin=73546
    CharacterOffsetEnd=73551 PartOfSpeech=VB Lemma=unite] [Text=!
    CharacterOffsetBegin=73551 CharacterOffsetEnd=73552 PartOfSpeech=. Lemma=!]
    /* ...more text below */

我想要做的是将Text=Lemma=给出的字符串提取到一个数组中。例如,对于上面的输出文本将是:

 WORKING
 work
 MEN
 man
 OF
 of

等等。我试过的:

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

#define MAX_LINE 4096

int main()
{
  FILE *fp;
  fp = fopen("moby.txt.out", "r");

  char *linha = malloc(MAX_LINE);
  int s, t;
  char lemma[100];

  while(fgets(linha, MAX_LINE, fp))
  {
    if(sscanf(linha, "Sentence #%d (%d tokens):", &s, &t))
    {
      /*printf("%d\n", t);*/
    }
    else if(sscanf(linha, "Lemma=%s", lemma))
    {
      printf("%s", lemma);
    }
}

fclose(fp);
return 0;
}

我不能使用外部库。我知道正则表达式不是 C 语言的一部分,所以欢迎任何帮助。

谢谢!

4

1 回答 1

8

无论如何,你甚至不需要正则表达式。也不是scanf()。一个简单的解决方案是使用strstr().

const char *s = "[Text=WORKING CharacterOffsetBegin=73516 CharacterOffsetEnd=73523 PartOfSpeech=VBG \
    Lemma=work] [Text=MEN CharacterOffsetBegin=73524 CharacterOffsetEnd=73527 \
    PartOfSpeech=NNS Lemma=man]";

const char *p = s;
while ((p = strstr(p, "Text=")) != NULL) {
    p += 5;
    const char *t = strchr(p, ' ');
    printf("%.*s\n", (int)(t - p), p);

    p = strstr(t + 1, "Lemma=") + 6;
    t = strchr(p, ']');
    printf("%.*s\n", (int)(t - p), p);
    p = t + 1;
}
于 2013-05-28T17:49:50.027 回答