【问题标题】:Trying to remove punctuation and count words尝试删除标点符号并计算单词
【发布时间】:2016-07-23 04:43:28
【问题描述】:

我正在尝试删除单词中的所有标点符号。该程序读取一个文件,然后使用哈希计算每个单词的所有出现次数。它主要工作。当我遇到这条线时,我遇到了麻烦

, , ,  , , , , , ,  . ./  . /   !@#$%^&*()_(&*^%&^%$%$%##%$%$# %%%$  ^%%^ % ^ %^&^ &^ &^ &^&^ &^ &^ &^ &^ %^% ^ % %$ %$ %$

我的程序打印出“, 32

如果有单词会打印出来

“单词,数字”

但是对于这种情况,它会打印出我假设的空字符串,并且我尝试过

这是我的主要文件。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#include"hash.h"

#define SIZE 5000

void fileRead(char * filename);
void fileWrite();
void removep(char * p);
struct listnode * hashTable[9000];

int main(int argc, char ** argv){
    int i;
    if(argc<2)
        fprintf(stderr,"Enter filename \n");

    hashCreate(hashTable, SIZE);

    for(i=1; i<argc; i++){
        fileRead(argv[i]);
    }

    fileWrite();
    hashDelete(hashTable, SIZE);
    return 0;
}

void fileWrite(){
    FILE * file=fopen("wordfrequency.txt","w");
    int i;
    struct listnode * temp;
    for(i=0;i<SIZE;i++){
        temp=hashTable[i];
        if(hashTable[i]->count!=0){
            for(temp=hashTable[i]; temp!=NULL; temp=temp->next){
                fprintf(file,"%s, %d\n",temp->word, temp->count);
            }
        }
    }
    fclose(file);
}

void fileRead(char * filename){
    FILE * file = fopen(filename,"r");
    char word[500];
    if(!file){
        fprintf(stderr,"Error opening file \n");
        return;
    }
    while(fscanf(file, "%s", word)==1){
        removep(word);
        if(word!=NULL || word[0]!='\0')
            hashAdd(word,hashTable,SIZE);
    }
    fclose(file);
}

void removep(char *p)
{
    char *src = p, *dst = p;

    while (*src)
    {
       if (ispunct((unsigned char)*src))
       {
          src++;
       }
       else if (isupper((unsigned char)*src))
       {
          *dst++ = tolower((unsigned char)*src);
          src++;
       }
       else if (src == dst)
       {
          src++;
          dst++;
       }
       else
       {
          *dst++ = *src++;
       }
    }

    *dst = 0;
}

【问题讨论】:

  • 仅供参考,fileReadif(word!=NULL || word[0]!='\0')始终为真,因为 word永远NULL,因此你总是散列和插入。基本数组永远不能是NULL。数组不是指针。该子句应该是if (*word)
  • 请不要在您的问题中包含未使用的代码 - 它会使其成为 MCVE (minimal reproducible example) 以外的其他内容,因为根据定义,未使用的代码意味着它不是最小的。跨度>
  • 我认为 WhozCraig 找到了一条关键线,但 || 可能是 &amp;&amp;,然后事情会变得更好——但你可以像 WhozCraig 所说的那样删除第一个子句。就个人而言,我更愿意看到if (word[0] != '\0') 而不是if (*word),但它们是等价的,这是一个品味问题。

标签: c string file-io


【解决方案1】:

我想通了。我变了

if(word!=NULL || word[0]!='\0')

if(word[0]!=' ' && word[0]!='\0')

现在它可以完美运行了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    • 1970-01-01
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多