[英]C Program to count the word frequency in a text file
我需要能夠用C編程編寫一個代碼,該代碼可以讀取文本文件,並找到每個單詞有多少個,並輸出該單詞及其出現的次數。 現在,我有可以打印出每個單詞及其出現次數的代碼,但是我需要它按字母順序打印並忽略大寫字母。 例如,“ It”和“ it”應計為同一單詞。 我不確定我的代碼中哪里包含修訂。 以下是我的代碼示例。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc == 1) {
printf("The input file name has not been provided\n");
} else if (argc == 2) {
FILE *f = fopen(argv[1], "rb");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET);
char *str = malloc(fsize + 1);
fread(str, fsize, 1, f);
fclose(f);
str[fsize] = 0;
int count = 0, c = 0, i, j = 0, k, space = 0;
char p[1000][512], str1[512], ptr1[1000][512];
char *ptr;
for (i = 0; i < strlen(str); i++) {
if ((str[i] == ' ') || (str[i] == ',') || (str[i] == '.')) {
space++;
}
}
for (i = 0, j = 0, k = 0; j < strlen(str); j++) {
if ((str[j] == ' ') || (str[j] == 44) || (str[j] == 46)) {
p[i][k] = '\0';
i++;
k = 0;
} else
p[i][k++] = str[j];
}
k = 0;
for (i = 0; i <= space; i++) {
for (j = 0; j <= space; j++) {
if (i == j) {
strcpy(ptr1[k], p[i]);
k++;
count++;
break;
} else {
if (strcmp(ptr1[j], p[i]) != 0)
continue;
else
break;
}
}
}
for (i = 0; i < count; i++) {
for (j = 0; j <= space; j++) {
if (strcmp(ptr1[i], p[j]) == 0)
c++;
}
printf("%s %d \n", ptr1[i], c);
c = 0;
}
}
return 0;
}
這是一個最小的命題,您的代碼可能需要分解為函數,但是請考慮這只是某種命題草案。 您只需將strcmp
替換為區分大小寫的部分的strcasecmp
。
然后,可以使用qsort
進行排序:定義一個用於比較的函數,例如:
int compar(const void *a, const void *b)
{
return *(char *)a - *(char *)b;
}
並將其應用於您的單詞數組。 據我了解,ptr1似乎可以保留您的話語,因此您可以添加
qsort(ptr1, count, sizeof(ptr1[0]), compar);
在最后一個for循環之前。
盡管如此,在我看來,由於valgrind報告代碼中的某些錯誤,您需要修復提取循環。
這是使用牛奶串函數的示例函數
typedef struct tWord {
tXt tx ;
int count ;
struct tWord * next ; } tWord;
typedef struct tWord *pWord;
void wordfrequency(void) {
pWord np,prev,bprev,most,allword ;
allword = NULL ;
FILE * fi = fopen("sample.txt","r") ;
if (fi == NULL)
return ;
tXt rlin = " " ;
while (rlin != txtEndFile) {
tXt lin = txtUpcase(txtTrim(rlin = txtFromFile(fi))) ;
while (lin[0]) {
tXt wrd = txtTrim(txtEat(&lin,' ')) ;
np = allword ;
while (np) {
if (strcmp(np->tx,wrd) == 0) {
np->count++ ;
wrd = "" ;
np = NULL ;
}
else
np = np->next ;}
if (wrd[0]) {
np = (pWord) malloc(sizeof(tWord)) ;
np->tx = fridge(wrd) ;
np->count = 1 ;
np->next = allword ;
allword = np ; } } }
while (allword) {
prev = bprev = NULL ;
np = most = allword ;
while (np) {
if (strcmp(most->tx , np->tx) >0 ) {
most = np ;
bprev = prev ; }
prev = np ;
np = np->next ; }
printf("%5d %s\n",most->count,unfridge(most->tx)) ;
if (bprev)
bprev->next = most->next ;
else
allword = most->next ;
free (most) ; }
fclose(fi) ;
if (txtAnyError())
printf("%s\n",txtLastError()) ;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.