如何计算字的幻影和排序 [英] How to count apparition of words and sort them

查看:130
本文介绍了如何计算字的幻影和排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到这个问题,我决定在这里问一个解决方案。我收到一个输入文件,其中包含单词和标点。我必须按字母顺序对这些字进行排序,并计算这个字的幻象。我解决了一半的问题,通过排除所有的标点,并把它们放在一个向量。但是,现在我遇到问题。我也知道排序的词(泡沫排序),但我不知道如何结合排序与幻象。如果有人帮助我,我会很高兴。

I encountered this problem, and I decided to ask here for a solution. I receive an input file, which contains words and puncts. I have to sort these words alphabetically, and count the apparition of this word. I solved half of the problem, by excluding all the puncts and putting them in a vector. But, now I encounter problem. I kinda know to sort the words (bubble sort), but I don't know how to combine the sort with the apparition. I would be glad if someone helped me.

例如,如果我收到这个输入:Ana are doua mere,unul verde si unul rosu。

For example, If I receive this input: Ana are doua mere, unul verde si unul rosu.

在输出中,我应该有:Ana 1,are 1,doua 1,mere 1,rosu 1,si 1,unul 2,verde 1。

In output I should have : Ana 1 ,are 1 ,doua 1 ,mere 1,rosu 1, si 1 ,unul 2,verde 1.

到目前为止我做了什么:

What I have done until now:

ifstream f(input_file_name);
ofstream g(output_file_name);
int nr=0,i,j;
char s[100],new_s[50][100],aux[100],*sterge;
while(!f.eof())
{
    f.get(s,100);
    sterge = strtok(s,",.?!:;");
    while(sterge)
    {
        nr++;
        strcpy(new_s[nr],sterge);
        sterge = strtok(NULL,",.?!:;");
    }
    f.get();

s是char,我从输入文件中读取; and new_s是一个字符,其中我只有没有任何(。;, - ..等等)

s is the char, where I read from the input file; and new_s is the char where I have only the words without any (.;,-.. and so on)

推荐答案

这标记为 c ++ ,我建议你使用它的功能。

As this is tagged c++, I suggest you to use it's functionalities.

对于这个任务, std :: map (默认为你的单词),用 std :: string 作为键(字)和一些int做计数。

For this task, I'd use a std::map (which will order your words by default), with std::string as key (word) and some int to do the counting.

#include <iostream>
#include <string>
#include <sstream>
#include <map>
#include <functional>
#include <algorithm>

int main()
{
    std::stringstream ss {"ab! ab .ab !?ab ...ab?! 3434 Ab aB AB"};

    std::map<std::string, int> words;
    std::string word;
    while(ss >> word)
    {
        // replace all characters that are not std::isalpha with space
        std::replace_if(word.begin(), word.end(), std::not1(std::ptr_fun<int,int>(&std::isalpha)), ' ');
        // remove spaces, and check if the word is valid (not all spaces)
        if(word.erase(std::remove_if(word.begin(), word.end(), std::ptr_fun<int,int>(&std::isspace)), word.end()) != word.begin())
            words[word] ++;
    }

    for(auto & w : words)
        std::cout << w.first << " " << w.second << "\n";
}

(只需更改 stringstream 为您的文件输入)

(just change stringstream for your file input)

实例

这篇关于如何计算字的幻影和排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆