C ++从文件中搜索特定单词的一行,然后在这些单词后插入一个单词

时间:2015-02-13 19:55:21

标签: c++ file capitalization

我是C ++的新手,我一直在努力寻找如何解决这个问题。基本上,我需要从文件中读取并找到文章的所有实例(“a”,“A”,“an”,“aN”,“An”,“AN”,“the”,“The”,“ “是”,“是”,“是”,“tHE”,“是”,“THE”然后在该文章之后插入一个形容词。形容词的大小写必须基于文章前面的单词。例如,如果我发现“一个鲨鱼”,我需要让它成为“一个快乐的鲨鱼”。谁能告诉我这样做的最佳方法是什么?到目前为止,我已经废弃了很多想法,这就是我现在拥有的,虽然我不认为我能这样做:

#include <iostream>
#include <string>
#include <cctype>
#include <fstream>
#include <sstream>

using namespace std;

void
usage(char *progname, string msg){
    cerr << "Error: " << msg << endl;
    cerr << "Usage is: " << progname << " [filename]" << endl;
    cerr << " specifying filename reads from that file; no filename reads standard input" << endl;
}

int main(int argc, char *argv[])
{
    string adj;
    string file;
    string line;
    string articles[14] = {"a","A","an","aN","An","AN","the","The","tHe","thE","THe","tHE","ThE","THE"};
    ifstream rfile;
    cin >> adj;
    cin >> file;
    rfile.open(file.c_str());
    if(rfile.fail()){
        cerr << "Error while attempting to open the file." << endl;
        return 0;
    }
    while(rfile.good()){
        getline(rfile,line,'\n');
        istringstream iss(line);
        string word;
        while(iss >> word){
            for(int i = 0; i <= 14; i++){
                if(word == articles[i]){
                    cout << word + " " << endl;
                }else{
                    continue;
                }
            }
        }
        }
  }

2 个答案:

答案 0 :(得分:1)

到目前为止,还不错,虽然如果你需要在一行的末尾处理一篇文章,那么你可能会遇到麻烦这样做。

无论如何,在你与一篇文章匹配之后,忽略了这种皱纹,那么首先你需要得到你需要根据大写字母确定的下一个词。然后你需要创建一个具有正确大小写的形容词的新字符串版本:

string adj_buf;  // big enough or dynamically allocate it based on adj

while(iss >> word){
    for(int i = 0; i <= 14; i++){
        if(word == articles[i]){
            cout << word + " ";
            iss >> word;  // TODO: check return value and handle no more words on this line
            adj_buf = adj;
            for (j = 0; j < word.size() && j < adj.size(); ++j)
                if (isupper(word[j]))
                    adj_buf[j] = toupper(adj[j]);
                else
                    adj_buf[j] = tolower(adj[j]);

            cout << adj_buf + " " + word;
            break;
        }
    }
}

回到皱纹我们忽略了。您可能不希望逐行执行此操作,然后通过令牌执行此操作,因为处理此特殊情况在您的控件中将会很难看。相反,您可能希望在单个循环中通过令牌进行令牌。

因此,您需要编写一个对文件进行操作的辅助函数或类,并为您提供下一个标记。 (STL中可能已经有这样一个类,我不确定。)无论如何,使用你的I / O可能看起来像:

struct FileTokenizer
{
    FileTokenizer(string fileName) : rfile(fileName) {}

    bool getNextToken(string &token)
    {
        while (!(iss >> token))
        {
            string line;

            if (!rfile.getline(rfile, line, '\n'))
                return false;

            iss.reset(line);  // TODO: I don't know the actual call to reset it; look it up
        }

        return true;
    }

private:
    ifstream      rfile;
    istringstream iss;
};

然后你的主循环看起来像:

FileTokenizer tokenizer(file);

while (tokenizer.getNextToken(word))
{
    for(int i = 0; i <= 14; i++){
        if(word == articles[i]){
            cout << word + " ";

            if (!tokenizer.getNextToken(word))
                break; 

            adj_buf = adj;
            for (j = 0; j < word.size() && j < adj.size(); ++j)
                if (isupper(word[j]))
                    adj_buf[j] = toupper(adj[j]);
                else
                    adj_buf[j] = tolower(adj[j]);

            cout << adj_buf + " " + word;
            break;
        }
    }
}

你可能也希望输出其余的输入?

答案 1 :(得分:0)

首先,我建议你使用3个辅助函数来转换字符串情况。如果您使用文本进行大量工作,这些将非常有用。这里它们基于<algorithm>many other aproaches are possible

string strtoupper(const string& s) {   // return the uppercase of the string
    string str = s; 
    std::transform(str.begin(), str.end(), str.begin(), ::toupper);
    return str; 
}
string strtolower(const string& s) {    // return the lowercase of the string
    string str = s;
    std::transform(str.begin(), str.end(), str.begin(), ::tolower);
    return str;
}
string strcapitalize (const string& s) {  // return the capitalisation (1 upper, rest lower) of the string
    string str = s;
    std::transform(str.begin(), str.end(), str.begin(), ::tolower);
    if (str.size() > 0)
        str[0] = toupper(str[0]); 
    return str;
}

然后是一个实用程序函数来克隆单词的大小写:它将形容词设置为小写或大写,或者将其大写(1大写+休息更低)复制引用单词的大小写。它足够强大,可以处理空单词,以及不是alaphanumeric的单词:

string clone_capitalisation(const string& a, const string& w) {
    if (w.size() == 0 || !isalpha(w[0]))  // empty or not a letter
        return a;                         //   => use adj as it is
    else {
        if (islower(w[0]))   // lowercase
            return strtolower(a);
        else return w.size() == 1 || isupper(w[1]) ? strtoupper(a) : strcapitalize(a);
    }
}

所有这些功能都不会改变原始字符串!

现在到main():我不喜欢手动放置文章的大小写的所有可能组合,所以我只使用大写。

我不喜欢按顺序浏览每个单词的所有可能的文章。如果会有更多的文章,它将不会是非常高效的!所以我更喜欢使用<set>

...
set<string> articles  { "A", "AN", "THE" };   // shorter isn't it ? 
...
while (getline(rfile, line)) {
    istringstream iss(line);
    string word;
    while (iss >> word) {     // loop 
        cout << word << " ";  // output the word in any case
        if (articles.find(strtoupper(word))!=articles.end()) {  // article found ?
            if (iss >> word) {  // then read the next word
                cout << clone_capitalisation(adj, word) << " " << word << " ";
            }
            else cout << word;  // if case there is no next word on the line...
        }
    }
    cout << endl; 
}