繁体   English   中英

C ++如何从文本文件中读取短语?

[英]C++ How can I read phrases from a text file?

我目前正在使用它从文本文件中一次读取1个单词:

int Dictionary::processFile(string file) {    //receives a text file name to be read from user
    string word;
    int wordCount = 0;

    ifstream fin;
    fin.open(file.c_str());
    if (fin.fail( )) {
        cout << endl;
        cout << "Input file opening failed.\n";
        return 0;
    }

    while (fin >> word) {
        word = trimString(word);    //trimString removes any symbols including spaces and words. only reads words.
        exTree.ExtAvlTree_processNode(word);    //processNode simply inserts the word into an avl tree. irrelevant to the question
        wordCount++;
    }
    fin.close();
    return wordCount;
}

我如何修改它以便能够在处理单词之前一次读取2-3个单词。 例如,它读取一个单词,然后对其进行处理,然后读取相同的单词,但添加下一个相邻单词,因此它成为一个短语(由2个单词组成),然后读取相同的2个单词,但将第三个下一个单词添加为另一个短语。

额外的问题,如果以上是可以实现的:

如何停止trimString函数删除空格并仅删除符号?

这是修剪字符串函数:

 string Dictionary::trimString(string input){
    stringstream ss;
    for (int x = 0; x < (int) input.size(); x++) {
        if(isalpha(input[x])){
            ss << input[x];
        }
    }

    if (ss.str().length() > 0) {
        return ss.str();
    } else {
        return "";
    }
}

您可以将读取的每个单词添加到std :: vector中,然后可以使用for循环以您描述的方式使用它们。 以下代码是您可以执行的操作示例

  vector<string> words;
  string word = "";
  ifstream infile("words.txt", ios::in);

  while (infile >> word)
  {
    /*
     you can process each word here like removing commas, periods 
     and such(if that is in fact what you want) before you add 
     them to the vector
    */
    words.push_back(word);
  }

  string phrase = "";

  for (int k = 0; k < words.size(); k++)
  {
    phrase +=  " " + words[k];
    cout << phrase << endl;
  }

在示例中,我假设您希望短语中的单词以空格分隔

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM