生成一个可进行文本分析的C语言代码
时间: 2024-05-01 13:21:27 浏览: 13
以下是一个简单的示例,用于将文本文件中的单词进行计数:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_WORD_LENGTH 50
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
exit(1);
}
char *filename = argv[1];
FILE *file = fopen(filename, "r");
if (file == NULL) {
fprintf(stderr, "Could not open file: %s\n", filename);
exit(1);
}
char word[MAX_WORD_LENGTH];
int count = 0;
while (fscanf(file, "%s", word) != EOF) {
// convert word to lowercase
for (int i = 0; i < strlen(word); i++) {
word[i] = tolower(word[i]);
}
// remove non-alphabetic characters from beginning and end of word
int start = 0;
while (!isalpha(word[start])) {
start++;
}
int end = strlen(word) - 1;
while (!isalpha(word[end])) {
end--;
}
word[end + 1] = '\0';
strcpy(word, &word[start]);
// increment count for word
if (strlen(word) > 0) {
count++;
}
}
printf("Total words: %d\n", count);
fclose(file);
return 0;
}
```
该代码假定单词之间用空格分隔,可以在 Linux 或 macOS 系统上编译运行。它将输出文件中单词的总数。您可以根据需要添加其他文本分析功能。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)