C++ C++;识别单词在句子中出现的频率

C++ C++;识别单词在句子中出现的频率,c++,C++,用于此任务的最佳STL是什么?我一直在使用Map, 但我无法让它工作。我不确定该如何检查句子中出现的相同单词的数量,例如: 我爱他,我爱她,他爱她 所以我想让程序提示用户输入一个整数,比如说我输入3,输出将是love,因为同一个单词在句子中出现了3次。但是如果我想做这样一个程序,应该使用什么方法呢 目前,我的程序提示用户输入单词,然后返回单词出现的次数,对于单词love,是3。但现在我想反过来。能做到吗?使用哪个STL更好?我假设您使用一个映射来存储出现的次数。 首先,您必须了解这一点,因为您使

用于此任务的最佳STL是什么?我一直在使用
Map
, 但我无法让它工作。我不确定该如何检查句子中出现的相同单词的数量,例如:

我爱他,我爱她,他爱她

所以我想让程序提示用户输入一个整数,比如说我输入3,输出将是love,因为同一个单词在句子中出现了3次。但是如果我想做这样一个程序,应该使用什么方法呢


目前,我的程序提示用户输入单词,然后返回单词出现的次数,对于单词love,是3。但现在我想反过来。能做到吗?使用哪个STL更好?

我假设您使用一个映射来存储出现的次数。 首先,您必须了解这一点,因为您使用的是地图,所以密钥是唯一的,而存储的数据可能不是唯一的。 考虑一张地图,X 有内容

x["I"]=3
x["Love"]=3
x["C"]=5
从键到值的映射是唯一的,而不是相反的,如果您想要这种一对一的映射,我建议使用不同的数据结构。如果您想要使用映射,并且仍然使用STL搜索功能或您自己的搜索功能搜索元素。或者您可以编写搜索功能。

map::迭代器ser;
cin>>检查;
对于(ser=x.begin();ser!=x.end();++ser)
{
如果(ser->秒==检查)
{

cout首先构建从单词到计数的映射,然后在此基础上构建反向多重映射。最后,您可以确定哪些单词以给定频率出现:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <utility>

int main()
{
    std::string str("I love him, I love her, he love her");
    std::istringstream ss(str);
    std::istream_iterator<std::string> begin(ss);
    std::istream_iterator<std::string> end;

    std::map<std::string, int> word_count;
    std::for_each(begin, end, [&](const std::string& s)
    {
        ++word_count[s];
    });

    std::multimap<int, std::string> count_words;
    std::for_each(word_count.begin(), word_count.end(),
                  [&](const std::pair<std::string, int>& p)
    {
        count_words.insert(std::make_pair(p.second, p.first));
    });

    auto its = count_words.equal_range(3);
    std::for_each(its.first, its.second,
                  [](const std::pair<int, std::string>& p)
    {
        std::cout << p.second << std::endl;
    });
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
int main()
{
string str(“我爱他,我爱她,他爱她”);
std::istringstream ss(str);
std::istream_迭代器begin(ss);
std::istream_迭代器端;
标准::映射字数;
std::for_each(开始、结束、[&](常量std::string&s)
{
++字数;
});
std::多映射计数\u字;
std::for_each(word_count.begin()、word_count.end(),
[&](const std::pair&p)
{
计数单词。插入(std::make_pair(p.second,p.first));
});
自动its=计数字。相等范围(3);
std::每个_(第一个,第二个,
[](常数标准::对和对)
{
标准::cout
/******************************************************************
姓名:保罗·罗杰斯
资料来源:HW1.CPP
编译程序:Visual C++
措施:程序将从标准输入读取并确定
在输入中找到的字长频率。适当的
也将显示表格。最大字长为15个字符
大于15的单词计为长度15。
还显示了平均字长。
注:单词包括连字符和带撇号的单词
撇号,即Jim的撇号,将撇号作为
字长。若单词在同一行,则连字符计数,否则不计数。
此外,int数组用于保存带有
与匹配下标关联的长度,下标为0
未使用。因此下标1对应于字长1,
下标2到字长2,依此类推。
------------------------------------------------------------------------*/
#包括
#包括
#包括
使用名称空间std;
int NextWordLength(void);//函数原型
void DisplayFrequencyTable(const int Words[]);
const int WORD_LENGTH=16;//数组的全局常量
void main()
{
int-WordLength;//单词0到X的实际长度
int NumOfWords[WORD_LENGTH]={0};//数组包含#个单词长度
WordLength=NextWordLength();
while(WordLength)//继续循环直到没有单词,即0
{//增量长度计数器
(字长
#包括
#包括
#包括
#包括
#包括
使用std::cout;
使用std::cin;
使用std::string;
使用std::endl;
使用std::vector;
使用std::map;
int main(){

仅供参考,这并不能正确解释输入字符串中的其他标点符号,例如,
her、
her
word\u count
中与“him”一起有单独的条目。您可能需要对word\u count进行后处理,以去除非字母字符并重新标记或丢弃。断字和其他嵌入的非字母字符是最常见的问题不大。Ser是映射的迭代器。嗨,Paul。谢谢你的代码片段。但是你确定这会有帮助吗?从长远来看,解释你所做的事情和示例代码会帮助更多。代码可能只是在不理解甚至阅读的情况下被复制。在这种情况下,代码似乎无法解决上述问题:)答案只是一段没有解释的代码,没有用处。请花时间解释一下这段代码是如何回答OP的问题的。
#include <algorithm>
#include <iostream>
#include <iterator>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <utility>

int main()
{
    std::string str("I love him, I love her, he love her");
    std::istringstream ss(str);
    std::istream_iterator<std::string> begin(ss);
    std::istream_iterator<std::string> end;

    std::map<std::string, int> word_count;
    std::for_each(begin, end, [&](const std::string& s)
    {
        ++word_count[s];
    });

    std::multimap<int, std::string> count_words;
    std::for_each(word_count.begin(), word_count.end(),
                  [&](const std::pair<std::string, int>& p)
    {
        count_words.insert(std::make_pair(p.second, p.first));
    });

    auto its = count_words.equal_range(3);
    std::for_each(its.first, its.second,
                  [](const std::pair<int, std::string>& p)
    {
        std::cout << p.second << std::endl;
    });
}
/******************************************************************
Name  :  Paul Rodgers
Source : HW1.CPP
Compiler :  Visual C++ .NET
Action : Program will read in from standard input and determine the
         frequency of word lengths found in input.  An appropriate
         table is also displayed.  Maximum word length is 15 characters
         words greater then 15 are counted as length 15. 
         Average word length also displayed.

Note   : Words include hyphenated and ones with apostrophes.  Words with
         apostrophes, i.e. Jim's, will count the apostrophe as part of the
         word length. Hyphen is counted if word on same line, else not.

         Also an int array is used to hold the number of words with
         length associated with matching subscript, with subscript 0
         not being used.  So subscript 1 corresponds to word length of 1,
         subscript 2 to word length of 2 and so on.
------------------------------------------------------------------------*/
#include <iostream>
#include <ctype.h>
#include <iomanip>
using namespace std;

int NextWordLength(void);                    // function prototypes
void DisplayFrequencyTable(const int Words[]);

const int WORD_LENGTH = 16;                // global constant for array

void main()
{
  int WordLength;                         // actual length of word 0 to X
  int NumOfWords[WORD_LENGTH] = {0};     // array holds # of lengths of words

  WordLength = NextWordLength();
  while (WordLength)                   // continue to loop until no word, i.e. 0
    {                                 // increment length counter
      (WordLength <= 14) ? (++NumOfWords[WordLength]) : (++NumOfWords[15]);
      WordLength = NextWordLength();
    }

  DisplayFrequencyTable(NumOfWords);
}

/**********************  NextWordLength  ********************************
Action  : Will determine the length of the next word. Hyphenated words and
          words with apostrophes are counted as one word accordingly
Parameters : none
Returns   : the length of word, 0 if none, i.e. end of file
-----------------------------------------------------------------------*/
int NextWordLength(void)
{
  char Ch;
  int EndOfWord = 0,       //tells when we have read in one word
      LengthOfWord = 0;

  Ch = cin.get();                           // get first character
  while (!cin.eof() && !EndOfWord)
   {
     while (isspace(Ch) || ispunct(Ch))      // Skips leading white spaces
        Ch = cin.get();                      // and leading punctation marks

     if (isalnum(Ch))          // if character is a letter or number
        ++LengthOfWord;        // then increment word length

     Ch = cin.get();           // get next character

     if ((Ch == '-') && (cin.peek() == '\n')) //check for hyphenated word over two lines
       {
         Ch = cin.get();       // don't count hyphen and remove the newline char
         Ch = cin.get();       // get next character then on next line
       }

     if ((Ch == '-') && (isalpha(cin.peek()))) //check for hyphenated word in one line
     {
         ++LengthOfWord;       // count the hyphen as part of word
         Ch = cin.get();       // get next character
     }

     if ((Ch == '\'') && (isalpha(cin.peek()))) // check for apostrophe in word
      {
        ++LengthOfWord;        // count apostrophe in word length
        Ch = cin.get();        // and get next letter
      }

     if (isspace(Ch) || ispunct(Ch) || cin.eof())  // is it end of word
       EndOfWord++;
   }

  return LengthOfWord;
}

/***********************  DisplayFrequencyTable  **************************
Action      :  Will display the frequency of length of words along with the
               average word length
Parameters
  IN        : Pointer to array holding the frequency of the lengths
Returns     : Nothing
Precondition: for loop does not go beyond WORD_LENGTH
------------------------------------------------------------------------*/
void DisplayFrequencyTable(const int Words[])
{
  int TotalWords = 0, TotalLength = 0;

  cout << "\nWord Length      Frequency\n";
  cout << "------------     ----------\n";

  for (int i = 1; i <= WORD_LENGTH-1; i++)
    {
     cout << setw(4) << i << setw(18) << Words[i] << endl;
     TotalLength += (i*Words[i]);
     TotalWords += Words[i];
    }

  cout << "\nAverage word length is ";

  if (TotalLength)
     cout << float(TotalLength)/TotalWords << endl;
  else
    cout << 0 << endl;
}
#include<iostream>
#include<string>
#include<vector>
#include<cstddef>
#include<map>

using std::cout;
using std::cin;
using std::string;
using std::endl;
using std::vector;
using std::map;

int main() {

    cout << "Please enter a string: " << endl;
    string str;
    getline(cin, str, '\n');

    size_t str_len = str.size();
    cout << endl << endl;

    size_t i = 0, j = 0;
    bool pop = false;

    map<string, int> myMap;

    for (size_t k = 0; k < str_len-1; k++) {
        if (((k == 0) && isalpha(str[0])) || (!(isalpha(str[k-1])) && isalpha(str[k])))
            i = k;
        if ( isalpha(str[k]) && !(isalpha(str[k+1])) ) {
            j = k;
            pop = true;
        }
        if ( (k == str_len-2) && isalpha(str[k+1]) ) {
            j = k+1;
            pop = true;
        }

        if ( (i <= j) && pop ) {
            string tmp = str.substr(i, j-i+1);
            cout << tmp << '\t';
            myMap[tmp]++;
            pop = false;
        }
    }
    cout << endl << endl;

    map<string, int>::iterator itr, end = myMap.end();
    for (itr = myMap.begin(); itr != end; itr++)
        cout << itr->first << "\t - - - - - \t" << itr->second << endl;

    cout << endl;

    return 0;
}