在C语言中创建.txt文件并对每个单词进行结构化处理的步骤如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char word[100];
int frequency;
} Word;
void processWords(const char* filename) {
FILE* file = fopen(filename, "r");
if (file == NULL) {
printf("无法打开文件\n");
return;
}
// 统计单词频率的哈希表
Word* wordList = (Word*)malloc(sizeof(Word) * 1000);
int wordCount = 0;
// 逐行读取文件内容
char line[1000];
while (fgets(line, sizeof(line), file)) {
char* token = strtok(line, " \t\n"); // 使用空格、制表符和换行符作为分隔符
while (token != NULL) {
// 将单词转换为小写
for (int i = 0; token[i]; i++) {
token[i] = tolower(token[i]);
}
// 检查单词是否已存在于哈希表中
int found = 0;
for (int i = 0; i < wordCount; i++) {
if (strcmp(wordList[i].word, token) == 0) {
wordList[i].frequency++;
found = 1;
break;
}
}
// 如果单词不存在,则将其添加到哈希表中
if (!found) {
strcpy(wordList[wordCount].word, token);
wordList[wordCount].frequency = 1;
wordCount++;
}
token = strtok(NULL, " \t\n");
}
}
fclose(file);
// 将结果写入新的.txt文件
FILE* outputFile = fopen("output.txt", "w");
if (outputFile == NULL) {
printf("无法创建输出文件\n");
free(wordList);
return;
}
for (int i = 0; i < wordCount; i++) {
fprintf(outputFile, "单词:%s,频率:%d\n", wordList[i].word, wordList[i].frequency);
}
fclose(outputFile);
free(wordList);
}
int main() {
const char* filename = "input.txt";
processWords(filename);
return 0;
}
这段代码将会读取名为"input.txt"的文件,统计其中每个单词的频率,并将结果写入名为"output.txt"的新文件中。你可以根据实际需求修改文件名和路径。
请注意,这里没有提及任何特定的云计算品牌商,因为这个问题与云计算无关。以上代码仅涉及C语言的文件处理和字符串处理,可以在任何支持C语言的环境中运行。
领取专属 10元无门槛券
手把手带您无忧上云