如果单词存在于单词数组中,则将其排除

时间:2019-05-16 09:24:04

标签: c

考虑到此代码可以计算所有出现的次数,您如何删除常用单词?

  

例如,如果该单词来自前100个英语单词,则不计算该单词。

如果您根据维基百科使用最常见的100个单词,则如何将它们添加到数组中并检查以使其不计入列表中: https://en.wikipedia.org/wiki/Most_common_words_in_English

数组形式的前100个最常用词:

#define NUMBER_OF_STRING 100
#define MAX_STRING_SIZE   50

char commonWords[NUMBER_OF_STRING][MAX_STRING_SIZE] = {"the", "be", "to", "of", "and", "a", "in", "that", "have", "I", "it", "for", "not", "on", "with", "he", "as", "you", "do", "at", "this", "but", "his", "by", "from", "they", "we", "say", "her", "she", "or", "an", "will", "my", "one", "all", "would", "there", "their", "what", "so", "up", "out", "if", "about", "who", "get", "which", "go", "me", "when", "make", "can", "like", "time", "no", "just", "him", "know", "take", "people", "into", "year", "your", "good", "some", "could", "them", "see", "other", "than", "then", "now", "look", "only", "come", "its", "over", "think", "also", "back", "after", "use", "two", "how", "our", "work", "first", "well", "way", "even", "new", "want", "because", "any", "these", "give", "day", "most", "us"};

代码示例:

/**
 * C program to count occurrences of all words in a file.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>

#define MAX_WORD  20000     /* max word size */
#define MAX_WORDS     8     /* initial number of struct to allocate */

#ifndef PATH_MAX
#define PATH_MAX   2048     /* max path (defined for Linux in limits.h) */
#endif

typedef struct {            /* use a struct to hold */
    char word[MAX_WORD];    /* lowercase word, and */
    int cap, count;         /* if it appeast capitalized, and its count */
} words_t;

char *strlwr (char *str)    /* no need for unsigned char */
{
    char *p = str;

    while (*p) {
        *p = tolower(*p);
        p++;
    }

    return str;
}

int main (void) {

    FILE *fptr;
    char path[PATH_MAX], word[MAX_WORD];
    size_t i, len, index = 0, max_words = MAX_WORDS;

    /* pointer to allocated block of max_words struct initialized zero */
    words_t *words = calloc (max_words, sizeof *words);
    if (!words) {   /* valdiate every allocation */
        perror ("calloc-words");
        exit (EXIT_FAILURE);
    }

    /* Input file path */
    printf ("Enter file path: ");
    if (scanf ("%s", path) != 1) {  /* validate every input */
        fputs ("error: invalid file path or cancellation.\n", stderr);
        return 1;
    }

    fptr = fopen (path, "r");   /* open file */
    if (fptr == NULL) {         /* validate file open */
        fputs ( "Unable to open file.\n"
                "Please check you have read privileges.\n", stderr);
        exit (EXIT_FAILURE);
    }

    while (fscanf (fptr, "%s", word) == 1) {  /* while valid word read */
        int iscap = 0, isunique = 1;    /* is captial, is unique flags */

        if (isupper (*word))            /* is the word uppercase */
            iscap = 1;

        /* remove all trailing punctuation characters */
        len = strlen (word);                    /* get length */
        while (len && ispunct(word[len - 1]))   /* only if len > 0 */
            word[--len] = 0;

        strlwr (word);                  /* convert word to lowercase */

        /* check if word exits in list of all distinct words */
        for (i = 0; i < index; i++) {
            if (strcmp(words[i].word, word) == 0) {
                isunique = 0;               /* set unique flag zero */
                if (iscap)                  /* if capital flag set */
                    words[i].cap = iscap;   /* set capital flag in struct */
                words[i].count++;           /* increment word count */
                break;                      /* bail - done */
            }
        }
        if (isunique) { /* if unique, add to array, increment index */
            if (index == max_words) {       /* is realloc needed? */
                /* always use a temporary pointer with realloc */
                void *tmp = realloc (words, 2 * max_words * sizeof *words);
                if (!tmp) { /* validate every allocation */
                    perror ("realloc-words");
                    break;  /* don't exit, original data still valid */
                }
                words = tmp;    /* assign reallocated block to words */
                /* (optional) set all new memory to zero */
                memset (words + max_words, 0, max_words * sizeof *words);
                max_words *= 2; /* update max_words to reflect new limit */
            }
            memcpy (words[index].word, word, len + 1);  /* have len */
            if (iscap)                      /* if cap flag set */
                words[index].cap = iscap;   /* set capital flag in struct */
            words[index++].count++;         /* increment count & index */
        }
    }
    fclose (fptr);  /* close file */

    /*
     * Print occurrences of all words in file.
     */
    puts ("\nOccurrences of all distinct words with Cap in file:");
    for (i = 0; i < index; i++) {
        if (words[i].cap) {
            strcpy (word, words[i].word);
            *word = toupper (*word);
            /*
             * %-15s prints string in 15 character width.
             * - is used to print string left align inside
             * 15 character width space.
             */
            printf("%-8d %s\n", words[i].count, word);
        }
    }
    free (words);

    return 0;
}

要测试的文本文件:(cars.txt)

A car (or automobile) is a wheeled motor vehicle used for transportation. Most definitions of car say they run primarily on roads, seat one to eight people, have four tires, and mainly transport people rather than goods.[2][3]

Cars came into global use during the 20th century, and developed economies depend on them. The year 1886 is regarded as the birth year of the modern car when German inventor Karl Benz patented his Benz Patent-Motorwagen. Cars became widely available in the early 20th century. One of the first cars accessible to the masses was the 1908 Model T, an American car manufactured by the Ford Motor Company. Cars were rapidly adopted in the US, where they replaced animal-drawn carriages and carts, but took much longer to be accepted in Western Europe and other parts of the world.

Cars have controls for driving, parking, passenger comfort, and a variety of lights. Over the decades, additional features and controls have been added to vehicles, making them progressively more complex. These include rear reversing cameras, air conditioning, navigation systems, and in-car entertainment. Most cars in use in the 2010s are propelled by an internal combustion engine, fueled by the combustion of fossil fuels. Electric cars, which were invented early in the history of the car, began to become commercially available in 2008.

There are costs and benefits to car use. The costs include acquiring the vehicle, interest payments (if the car is financed), repairs and maintenance, fuel, depreciation, driving time, parking fees, taxes, and insurance.[4] The costs to society include maintaining roads, land use, road congestion, air pollution, public health, health care, and disposing of the vehicle at the end of its life. Road traffic accidents are the largest cause of injury-related deaths worldwide.[5]

The benefits include on-demand transportation, mobility, independence, and convenience.[6] The societal benefits include economic benefits, such as job and wealth creation from the automotive industry, transportation provision, societal well-being from leisure and travel opportunities, and revenue generation from the taxes. People's ability to move flexibly from place to place has far-reaching implications for the nature of societies.[7] There are around 1 billion cars in use worldwide. The numbers are increasing rapidly, especially in China, India and other newly industrialized countries.[8]

当前输出:

Occurrences of all distinct words with Cap in file:
3        A
2        Motor
2        Most
2        One
8        Cars
29       The
1        German
1        Karl
2        Benz
1        Patent-motorwagen
1        Model
1        T
1        American
1        Ford
1        Company
1        Us
1        Western
1        Europe
1        Over
1        These
1        Electric
2        There
2        Road
1        People's
1        China
1        India

预期输出:(仅示例)

2        Motor
1        German
1        Karl
2        Benz
1        Patent-motorwagen
1        Model
1        T
1        American
1        Ford
1        Company

编辑更新: 可能的解决方案:

  • 同时继续操作(无效)

    // skip the word if it is a common word
    for (int i = 0; i < NUMBER_OF_STRING; i++) {
        if (strcmp(word, commonWords[i])==0) {
            continue;
        }
    }
    
  • 4 个答案:

    答案 0 :(得分:3)

    先过滤掉$(document).ready(function () { $(‘#login_dialog’).dialog({ autoOpen: true, draggable: false, modal: true, buttons: { “Connect”: function () { $(document).trigger(‘connect’, { jid: $(‘#jid’).val(), password: $(‘#password’).val() }); $(‘#password’).val(‘’); $(this).dialog(‘close’); } } }) ,然后再将import requests from getpass import getpass from bs4 import BeautifulSoup headers = { 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36' } login_data = { 'commit': 'Sign in', 'utf8': '%E2%9C%93', 'login': input('Username: '), 'password': getpass() } url = 'https://github.com/session' session = requests.Session() response = session.get(url, headers=headers) soup = BeautifulSoup(response.text, 'html5lib') login_data['authenticity_token'] = soup.find( 'input', attrs={'name': 'authenticity_token'})['value'] response = session.post(url, data=login_data, headers=headers) print(response.status_code) response = session.get('https://github.com', headers=headers) print(response.text) 添加到common word列表中。 我做了如下的拟合函数:

    word

    然后,在添加到word数组之前过滤掉单词。 请参考我修改的代码的第二行,如下所示:

    words

    我认为结果是正确的,如下所示:

    int isCommonWord(char * word)
    {
        int i = 0;
        for (i = 0; i < NUMBER_OF_STRING; i++) {
            if (strcmp(commonWords[i], word) == 0) return 1;
        }
        return 0;
    }
    

    答案 1 :(得分:3)

    一种稍微有效的方法是使用一次对strstr的调用,而不是尝试与前100个最常用的单词中的每个单词进行比较。由于您知道100个最常用的单词,并且它们不会改变,因此您可以轻松确定最长的7个字符。换句话说,如果word小于以下值,您只需测试#define TOP_LEN 8 /* longest string in TOP100 + nul-character */ 是否是最常见的之一:

    const char TOP100[] = " the be to of and a in that have i it for not on with"
                    " he as you do at this but his by from they we say her she or"
                    " an will my one all would there their what so up out if about"
                    " who get which go me when make can like time no just him know"
                    " take people into year your good some could them see other"
                    " than then now look only come its over think also back after"
                    " use two how our work first well way even new want because"
                    " any these give day most us ";
    

    由于单词不变,因此您可以继续进行以下操作:

    space

    注意:每个单词前面的space和后面的teststr,可让您创建strstr来搜索'I'在单词的两边加上空格。strlwr (word);已转换为小写字母,可以在#define TOP100 " the ... us "之后使用

    也请注意:,您也可以将常量文字与 ... strlwr (word); /* convert word to lowercase */ /* check against 100 most common words (TOP100) */ if (len < TOP_LEN) { /* word less than TOP_LEN? */ char teststr[TOP_LEN * 2]; /* buffer for " word " */ sprintf (teststr, " %s ", word); /* create teststr */ if (strstr (TOP100, teststr)) /* check if in TOP100 */ continue; /* if so, get next word */ } ... 一起使用,但是它会在此处折叠并滚动出整个页面-取决于您)

    使用100个最常见单词的恒定字符串,唯一需要添加的内容是:

    teststr

    您在上面看到,您检查单词是否等于或少于7个字符(否则,无需对照最常见的单词)。然后,您声明一个sprintf来在字符串的两端保留一个空格。 (由于7个字符中最长的普通单词,因此7个字符加2个空格为9个字符,加上 nul-character为 10,所以这里16个字符已足够了。)

    只需简单地调用word即可将空格放在strstr的每一端,然后只需调用一次word就可以查看是否continue在前100个最常用的单词内。如果是这样,则无需进一步,只需/** * C program to count occurrences of all words in a file. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <limits.h> #define MAX_WORD 20000 /* max word size */ #define MAX_WORDS 8 /* initial number of struct to allocate */ #define TOP_LEN 8 /* longest string in TOP100 */ #ifndef PATH_MAX #define PATH_MAX 2048 /* max path (defined for Linux in limits.h) */ #endif const char TOP100[] = " the be to of and a in that have i it for not on with" " he as you do at this but his by from they we say her she or" " an will my one all would there their what so up out if about" " who get which go me when make can like time no just him know" " take people into year your good some could them see other" " than then now look only come its over think also back after" " use two how our work first well way even new want because" " any these give day most us "; typedef struct { /* use a struct to hold */ char word[MAX_WORD]; /* lowercase word, and */ int cap, count; /* if it appeast capitalized, and its count */ } words_t; char *strlwr (char *str) /* no need for unsigned char */ { char *p = str; while (*p) { *p = tolower(*p); p++; } return str; } int main (void) { FILE *fptr; char path[PATH_MAX], word[MAX_WORD]; size_t i, len, index = 0, max_words = MAX_WORDS; /* pointer to allocated block of max_words struct initialized zero */ words_t *words = calloc (max_words, sizeof *words); if (!words) { /* valdiate every allocation */ perror ("calloc-words"); exit (EXIT_FAILURE); } /* Input file path */ printf ("Enter file path: "); if (scanf ("%s", path) != 1) { /* validate every input */ fputs ("error: invalid file path or cancellation.\n", stderr); return 1; } fptr = fopen (path, "r"); /* open file */ if (fptr == NULL) { /* validate file open */ fputs ( "Unable to open file.\n" "Please check you have read privileges.\n", stderr); exit (EXIT_FAILURE); } while (fscanf (fptr, "%s", word) == 1) { /* while valid word read */ int iscap = 0, isunique = 1; /* is captial, is unique flags */ if (isupper (*word)) /* is the word uppercase */ iscap = 1; /* remove all trailing punctuation characters */ len = strlen (word); /* get length */ while (len && ispunct(word[len - 1])) /* only if len > 0 */ word[--len] = 0; strlwr (word); /* convert word to lowercase */ /* check against 100 most common words (TOP100) */ if (len < TOP_LEN) { /* word less than TOP_LEN? */ char teststr[TOP_LEN * 2]; /* buffer for " word " */ sprintf (teststr, " %s ", word); /* create teststr */ if (strstr (TOP100, teststr)) /* check if in TOP100 */ continue; /* if so, get next word */ } /* check if word exits in list of all distinct words */ for (i = 0; i < index; i++) { if (strcmp(words[i].word, word) == 0) { isunique = 0; /* set unique flag zero */ if (iscap) /* if capital flag set */ words[i].cap = iscap; /* set capital flag in struct */ words[i].count++; /* increment word count */ break; /* bail - done */ } } if (isunique) { /* if unique, add to array, increment index */ if (index == max_words) { /* is realloc needed? */ /* always use a temporary pointer with realloc */ void *tmp = realloc (words, 2 * max_words * sizeof *words); if (!tmp) { /* validate every allocation */ perror ("realloc-words"); break; /* don't exit, original data still valid */ } words = tmp; /* assign reallocated block to words */ /* (optional) set all new memory to zero */ memset (words + max_words, 0, max_words * sizeof *words); max_words *= 2; /* update max_words to reflect new limit */ } memcpy (words[index].word, word, len + 1); /* have len */ if (iscap) /* if cap flag set */ words[index].cap = iscap; /* set capital flag in struct */ words[index++].count++; /* increment count & index */ } } fclose (fptr); /* close file */ /* * Print occurrences of all words in file. */ puts ("\nOccurrences of all distinct words with Cap in file:"); for (i = 0; i < index; i++) { if (words[i].cap) { strcpy (word, words[i].word); *word = toupper (*word); /* * %-15s prints string in 15 character width. * - is used to print string left align inside * 15 character width space. */ printf("%-8d %s\n", words[i].count, word); } } free (words); return 0; } 并得到下一个单词即可。

    将其完全放在您的代码中

    cars.txt

    使用/输出示例

    与上次一样,您的预期输出:(仅作为示例)是错误的,因为您的代码中没有任何内容可以删除复数 possessives < / em>或复数所有格,因此您的$ ./bin/unique_words_exclude_top_100 Enter file path: dat/cars.txt Occurrences of all distinct words with Cap in file: 2 Motor 8 Cars 1 German 1 Karl 2 Benz 1 Patent-motorwagen 1 Model 1 T 1 American 1 Ford 1 Company 1 Western 1 Europe 1 Electric 2 Road 1 People's 1 China 1 India 文件的输出为:

    html()

    仔细检查一下,如果还有其他问题,请告诉我。

    答案 2 :(得分:2)

    这显然是行不通的,因为它不会像误导性评论中那样,跳过一个普遍的单词,而是跳过当前的迭代,继续检查常用单词列表中的下一个单词

    // skip the word if it is a common word
    for (int i = 0; i < NUMBER_OF_STRING; i++) {
        if (strcmp(word, commonWords[i])==0) {
            continue;
        }
    }
    

    continue仅影响最内部的循环。此外,循环没有任何改变

    要解决此问题,您需要打破外循环

    nextword:
    while (fscanf (fptr, "%s", word) == 1) // read the word
        for (int i = 0; i < NUMBER_OF_STRING; i++) {
            if (strcmp(word, commonWords[i])==0) {
                goto nextword; // skip current word
            }
        }
    /// ...
    }
    

    或者,如果您不想使用goto,则必须使用另一个变量

    int isCommonWord = 0;
    while (fscanf (fptr, "%s", word) == 1) // read the word
        for (int i = 0; i < NUMBER_OF_STRING; i++) {
            if (strcmp(word, commonWords[i])==0) {
                isCommonWord = 1;
                break; // exit the for loop
            }
        }
        if (isCommonWord)
            continue;  // get the next word
    /// ...
    }
    

    无论如何,您的实现效率很低。这基本上是一个dictionary,它从字符串(单词)映射到整数(单词计数)。字典可以排序(例如C ++中的std::map)或hash-based(C ++中的std::unordered_map)。由于您不对数组进行排序,因此始终必须遍历整个列表。如果数组已排序,则使用binary search将大大减少查找。要检查一个包含128个元素的列表,您最多只需要进行7个比较,而不是像未排序列表那样进行128个比较

    但是在字典中查找单词之前,您需要先检查该单词是否常见。这可以通过检查常见单词set中是否存在该单词来完成。同样,该集合可以实现为未排序(慢),排序(更好,在C ++中为std::set)或基于散列的(最快,但需要更多内存,在C ++中为std::unordered_set)。集合和字典之间的区别在于,每个字典条目都包含一对(键,值),而值也是集合中的键。上面的for循环检查strcmp(word, commonWords[i])==0是一个简单的集合遍历。无论如何,一旦您在集合中找到单词,就跳过当前的while循环,而像我上面所说的那样,循环for。可以的

    答案 3 :(得分:0)

    建议继续使用goto

    在片刻之前添加标签:

    outer:
    while (fscanf (fptr, "%s", word) == 1)  { ... }
    

    并将问题中的可能解决方案更改为:

    for (int i = 0; i < NUMBER_OF_STRING; i++) {
        if (strcmp(word, commonWords[i])==0) {
            goto outer;
        }
    }
    

    在您当前的解决方案中,continue只是继续内部for循环。

    编辑


    根据您的程序,按如下所示修改程序即可:

    .
    .
    .
    
    outer:
    while (fscanf (fptr, "%s", word) == 1) {
        .
        .
        .
    
        strlwr(word);
    
        for (int i = 0; i < NUMBER_OF_STRING; i++) {
            if (strcmp(word, commonWords[i])==0) {
                goto outer;
            }
        }
    
        .
        .
        .
    }
    
    .
    .
    .
    

    用于此目的的功能如下:

    int isCommon(char *word) {
        for (int i = 0; i < NUMBER_OF_STRING; i++) {
            if (strcmp(word, commonWords[i])==0) {
                return 1;
            }
        }
        return 0;
    }
    
    int main() {
        .
        .
        .
    
        while (fscanf (fptr, "%s", word) == 1) {
            .
            .
            .
    
            strlwr(word);
    
            if(isCommon(word))
                continue;
    
            .
            .
            .
        }
    
        .
        .
        .
    }
    

    请注意,如果使用此功能,则不再需要goto;一个简单的continue就足够了。