zoukankan      html  css  js  c++  java
  • 软件工程设计:分析一个文本文件(英文文章)中各个词出现的频率,并且把频率最高的10个词打印出来。

    大学三年发现,学过好多语言,但是一遇到写程序就只有用C++了。虽然不是最简洁的那种,但是出于对c++的学习时间比较成的角度,用c++完成这个程序题还是可以应付的。

    下面我简单说说设计思路吧:

    从题目要求出发,是对于一个文本文件的分析,也就是需要对文件的读入和操作。

    void read_article(struct Word*&head)就是读取制定的文件的文章函数并统计次数。

    然后就是单词的储存题目,我第一个想到了链表,因为数组存在着内存分派题目。我想到可以定义一个数据类型来储存单词和它呈现的次数,然后在排序即可。

    char a,temp[300];
    struct Word *p;
    while(infile)    是用来储存单词和出现次数的。

    之后就是一些输出的程序了

    void out_file(struct Word*&head)结果输出到了文件中
    声明:对于这个程序单个字母统计不分大小写

    但是在程序的审查时,发现了一些不足之处:

    因为应用数组的思惟存储单词使合适读入文章过小时会浪费空间,过大时又须要改变参数,很不便利。并且因为读入时作为单词分别的是空格、换行,会把标点误判为单词 的一项目组。

    程序代码:

    #include<iostream>
    #include<string>
    #include<fstream>
    using namespace std;
    struct S
    {
    char *na;
    int N;
    struct S *next;
    };
    /*void out_file(struct S*&head)
    {
    ofstream outfile("out.txt");
    struct S *p;
    p=head->next;
    while(p)
    {
    outfile<<"单词"<<p->name<<endl<<"出现次数"<<p->num<<endl;
    p=p->next;
    }

    }*/
    void out(struct S*head,int n)
    {
    struct S *p;
    p=head->next;
    for(int i=0;i<n;i++)
    {
    cout<<"单词"<<p->na<<endl<<"出现次数"<<p->N<<endl;
    p=p->next;
    }
    }
    void getsort(struct S*&head)
    {
    struct S *p,*q,*s,*l;
    q=head;
    p=head->next;
    s=p->next;
    p->next=NULL;
    while(s)
    {
    while(p&&p->N>s->N)
    {
    q=p;
    p=p->next;
    }
    q->next=s;
    l=s->next;
    s->next=p;
    s=l;
    p=head->next;
    q=head;
    }
    }
    void read_article(struct S*&head)
    {
    ifstream infile("test.txt");
    infile>>noskipws;
    if(!infile) {
    cout<<"找不到相关文章!"<<endl;
    }
    char a,temp[30];
    struct S *p;
    while(infile)
    {
    int i=0;
    infile.get(a);
    temp[0]='';
    while((a>='a'&&a<='z')||(a>='A'&&a<='Z')||temp[0]=='')
    {
    if(a>='a'&&a<='z'||a>='A'&&a<='Z')
    {
    temp[i]=a;
    i++;
    }
    infile.get(a);
    if(infile.eof())break;

    }
    temp[i]='';
    p=head->next;
    while(p)
    {
    if(!_stricmp(temp,p->na))
    { p->N++;break;}
    p=p->next;
    }
    if(!p&&temp[0]!='')
    {
    p=new S;
    p->na=new char(i);
    strcpy(p->na,temp);
    p->N=1;
    p->next=head->next;
    head->next=p;
    }
    }
    infile.close();
    }
    int main()
    {
    struct S *head;
    head=new S;
    head->next=NULL;
    read_article(head);
    getsort(head);
    out(head,10);
    //out_file(head);
    return 0;
    }

  • 相关阅读:
    ​特征工程系列:特征预处理(上)
    特征工程系列:特征预处理(下)
    工具使用介绍
    Android图片处理
    Tomcat报java.lang.OutOfMemoryError: Java heap space错误停止运行如何解决
    JBOSS.71.1.Final安装配置
    android:windowSoftInputMode属性详解
    IOS入门之Swift语言(一)
    Android仿微信拍摄短视频
    Android实现播放视频
  • 原文地址:https://www.cnblogs.com/dongfangjian/p/3577378.html
Copyright © 2011-2022 走看看