2013-05-28 2 views
1

나는 다음과 같은 형식의 파일을 읽고 있어요 : 문자열이 텍스트에 의해 주어진 배열에추출 문자열 패턴 (NO libs와)

/* ...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 */ 

내가 뭘하고 싶은 것은 추출물에를 =보조 정리 =. 예를 들어 위의 텍스트는 다음과 같습니다.

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 언어의 일부가 아니므로 어떤 도움도 환영합니다.

감사합니다.

+1

정규식 라이브러리를 사용하지 않는 이유는 무엇입니까? 예 : http://www.gnu.org/software/libc/manual/html_node/Regular-Expressions.html –

+2

@ PaululR 아마도 필요한 것은 공백과 괄호로 구분 된 단어를 추출한 다음 정규 표현식 라이브러리는 상당히 잔인합니다. –

답변

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; 
} 
+0

참으로 .. 우수하고 빠른 답을 +1합니다! – Anirudha

+0

감사합니다. 완벽하게 작동했습니다. – Fernando