我正在阅读具有以下格式的文件:
/* ...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语言的一部分,所以欢迎任何帮助。
谢谢!
答案 0 :(得分: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;
}