[英]C Isolating “only strings” in a text file
我有一個文本文件,其中有1個單詞后跟~100個浮點數。 浮點數由空格,制表符或換行符分隔。 此格式在整個文本文件中重復多次。
例如,這就是文本文件的樣子:
one 0.00591 0.07272 -0.78274 ...
0.0673 ...
0.0897 ...
two 0.0654 ...
0.07843 ...
0.0873 ...
three ...
...
...
我的問題是,如何計算文件中的單詞數量,我嘗試使用fscanf但是一旦它讀取第一個單詞,之后我必須跳過所有浮點數直到下一個單詞。
任何幫助將非常感激。
謝謝。
我將為您提供一個可能的解決方案的高級概述,讓您自己弄清楚如何將其轉換為C.
您可能會發現一些有用的庫函數:
getline
讀取單行輸入。 它不是官方標准庫的一部分,而是作為許多實現的擴展提供的,包括GNU的libc。 如果你沒有它,你可以使用fgets
和realloc
自己動手。 strtok
標記一個字符串,雖然使用起來有點尷尬。 如果你想自己標記,你會發現isspace
很有用。 您將需要用NUL字節替換空白字符,以便將它們之間的字符視為單獨的NUL終止字符串。 strtod
嘗試將字符數組解析為double
。 您可以實現自己的小有限自動機,而不是使用庫函數將數字解析為double
。 這是自動機理論中的經典教學實例。 例如,參見本講座 (向下滾動“浮點數的語言”)。
這是一種逐字逐句的方法(不需要緩沖區)。 我很確定邏輯是合理的。
#include <stdio.h>
int is_alpha(char c)
{
//only works for some character encodings
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
int main(void)
{
FILE *file_ptr;
int character;
int prev_char_was_letter = 0;
int word_count = 0;
file_ptr = fopen("my_file.txt", "r");
if (!file_ptr)
{
fprintf(stderr, "can't open file\n");
return 1;
}
character = fgetc(file_ptr);
while (character != EOF)
{
if (is_alpha(character) && !prev_char_was_letter)
{
word_count++;
prev_char_was_letter = 1;
}
else if (!is_alpha(character))
{
prev_char_was_letter = 0;
}
character = fgetc(file_ptr);
}
printf("%d\n", word_count);
fclose(file_ptr);
}
已經建議的替代解決方案是使用strtok()進行分隔和isalpha()函數。 這是一個完成工作的程序示例。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char delim[4]={' ','\t',0x0a,0x0d};
#define MAX_LINE 1024
int isaword(char *);
int main(int argc,char **argv)
{
FILE *fp;
char line[MAX_LINE];
char *s;
int wcnt=0;
if(argc==1)
{
fp = stdin;
}
else
{
fp = fopen(argv[1],"r");
}
if(fp==0)
{
return -1; ///file not found
}
while(!feof(fp))
{
s=fgets(line,MAX_LINE,fp);
if(s)
{
s=strtok(line,delim);
while(s!=NULL)
{
if(isaword(s))
{
wcnt++;
}
s=strtok(NULL,delim);
}
}
}
fclose(fp);
printf("word count = %d",wcnt);
return 0;
}
int isaword(char *w)
{
int result = 1;
int i;
for(i=0;i<strlen(w);i++)
{
result = isalpha(w[i]);
if(result==0)
{
break;
}
}
return result;
}
解決方案中的免責聲明 - “單詞”的定義基於函數isalpha 。
你可以這樣做:
void foo() {
FILE *file = fopen("file.txt", "r");
char buffer[10000]; // your choice
while(fscanf(file, "%s", buffer) > 0) {
int i = 0;
int word = 0;
int number_of_dots = 0;
while(i < strlen(buffer)) {
if(!isdigit(buffer[i]) && buffer[i] != '.') {
if(!(i == 0 && buffer[i] == '-')) {
word = 1;
break;
}
}
if(buffer[i] == '.') number_of_dots++;
i++;
}
if(word || number_of_dots > 1) {
printf("%s ", buffer);
puts("It's a word!");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.