Reputation: 7905
I'm reading a file with the following format:
/* ...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 */
What i want to do is to extract into an array the strings given by Text= and Lemma=. For example, for the text above the output would be:
WORKING
work
MEN
man
OF
of
And so on. What i've tried:
#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;
}
I can't use external libs. I know regex is not part of C language, so any help is welcome.
Thanks!
Upvotes: 1
Views: 432
Reputation:
And anyways you don't even need regexes. Nor scanf()
. A simple solution is using 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;
}
Upvotes: 8