需求大概是:
在一個文本中,有幾萬個關鍵詞,需要篩選掉其中重復出現的詞,如下:
1、你好啊
2、你好
3、你
這個時候,只保留“你”這個關鍵詞,“你好啊”和“你好”都要去掉,因為,這兩個詞都包含“你”這個關鍵詞,求大佬指教下,代碼要怎么處理
uj5u.com熱心網友回復:
1、所有關鍵詞從短到長排序;2、從最短的開始,回圈遍歷比較,每次選擇一個關鍵詞,然后遍歷判斷后面的詞是否包含該關鍵詞,若包含,則洗掉對應關鍵詞;
uj5u.com熱心網友回復:
僅供參考://檔案1中的內容排序并去重,結果保存到檔案2中
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXCHARS 1024 //能處理的最大行寬,包括行尾的\n和字串尾的\0
int MAXLINES=10000,MAXLINES2;
char *buf,*buf2;
int c,n,hh,i,L;
FILE *f;
char ln[MAXCHARS];
int ignore_case=0;
int icompare(const void *arg1,const void *arg2) {
return stricmp((char *)arg1,(char *)arg2);
}
int compare(const void *arg1,const void *arg2) {
return strcmp((char *)arg1,(char *)arg2);
}
int main(int argc,char **argv) {
if (argc<3) {
printf("Unique line. Designed by [email protected]. 2012-08-20\n");
printf("Usage: %s src.txt uniqued.txt [-i]\n",argv[0]);
return 1;
}
if (argc>3) ignore_case=1;//若存在命令列引數3,忽略大小寫
f=fopen(argv[1],"r");
if (NULL==f) {
printf("Can not find file %s!\n",argv[1]);
return 1;
}
buf=(char *)malloc(MAXLINES*MAXCHARS);
if (NULL==buf) {
fclose(f);
printf("Can not malloc(%d LINES*%d CHARS)!\n",MAXLINES,MAXCHARS);
return 2;
}
n=0;
hh=0;
i=0;
while (1) {
if (NULL==fgets(ln,MAXCHARS,f)) break;//
hh++;
L=strlen(ln)-1;
if ('\n'!=ln[L]) {//超長行忽略后面內容
printf("%s Line %d too long(>%d),spilth ignored.\n",argv[1],hh,MAXCHARS);
while (1) {
c=fgetc(f);
if ('\n'==c || EOF==c) break;//
}
}
while (1) {//去掉行尾的'\n'和空格
if ('\n'==ln[L] || ' '==ln[L]) {
ln[L]=0;
L--;
if (L<0) break;//
} else break;//
}
if (L>=0) {
strcpy(buf+i,ln);i+=MAXCHARS;
n++;
if (n>=MAXLINES) {
MAXLINES2=MAXLINES*2;
if (MAXLINES2==1280000) MAXLINES2=2500000;
buf2=(char *)realloc(buf,MAXLINES2*MAXCHARS);
if (NULL==buf2) {
printf("Can not malloc(%d LINES*%d CHARS)!\n",MAXLINES2,MAXCHARS);
printf("WARNING: Lines >%d ignored.\n",MAXLINES);
break;//
}
buf=buf2;
MAXLINES=MAXLINES2;
}
}
}
fclose(f);
if (n>1) {
if (ignore_case) qsort(buf,n,MAXCHARS,icompare);
else qsort(buf,n,MAXCHARS,compare);
}
f=fopen(argv[2],"w");
if (NULL==f) {
free(buf);
printf("Can not create file %s!\n",argv[2]);
return 2;
}
fprintf(f,"%s\n",buf);
if (n>1) {
if (ignore_case) {
hh=0;
L=MAXCHARS;
for (i=1;i<n;i++) {
if (stricmp((const char *)buf+hh,(const char *)buf+L)) {
fprintf(f,"%s\n",buf+L);
}
hh=L;
L+=MAXCHARS;
}
} else {
hh=0;
L=MAXCHARS;
for (i=1;i<n;i++) {
if ( strcmp((const char *)buf+hh,(const char *)buf+L)) {
fprintf(f,"%s\n",buf+L);
}
hh=L;
L+=MAXCHARS;
}
}
}
fclose(f);
free(buf);
return 0;
}
uj5u.com熱心網友回復:
你好,會提示長度問題,我這邊的關鍵字,一共有50000+個,每行各一個

uj5u.com熱心網友回復:
你實際運行我的代碼了嗎?轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/256454.html
標籤:C++ 語言
下一篇:一個關于C語言資料型別的問題
