【问题标题】:How to iterate through a csv file and then split each column into a vector如何遍历 csv 文件,然后将每一列拆分为一个向量
【发布时间】:2021-01-10 16:05:01
【问题描述】:

所以我有一个包含 2 列的 CSV - 一个用于一首歌曲,一个用于该歌曲的艺术家。例如

The Pretender,Foo Fighters
In Bloom,Nivana
Champagne Supernova,Oasis
Starlight,Muse
Will We Talk?,Sam Fender

我正在将我写了一段时间的 python 程序转换回 c++。在该程序中,它使用 csv 库来读取 csv,并从中选择一个随机行。然后它将它分成两列,然后将它们存储在变量中,答案是歌曲名称,标题是歌曲名称:

    #select a random row and store it in a list
    randomrow = random.choice(list(csvreader))
    #print(randomrow)
    answer = randomrow[0]
    answer = answer.strip()
    #print(answer)

    track = randomrow[0]
    #print(track)
    #split track into two columns - title and artist
    title = track.split()

我已经尝试过这个帖子的技术:here

如:

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

std::ifstream songsCsv("Songs.csv");

std::string line;
while (std::getline(songsCsv line))
{
    std::istringstream iss(line);
    std::string song, artist;
    if (!(iss >> song >> artist)) { break; }

    cout << song;
    cout << artist;

}

但是,这里没有输出任何内容。如果有人对如何做到这一点有任何想法,我们将不胜感激。

【问题讨论】:

  • !(iss &gt;&gt; song &gt;&gt; artist) 是做什么的?
  • &gt;&gt; 不会将行分隔为逗号分隔值。 C++ 不能以这种方式工作。
  • 感谢跳过 Python 地狱(2 还是 3?) 您是否单步执行了代码?如果没有,试试吧,你会很容易找到解决办法的。

标签: python c++ csv vector


【解决方案1】:

根据您的 CSV 文件,您可以有这样的解决方案:

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

int main()
{
    std::vector<std::pair<std::string, std::string>> result;
    std::string line;
    std::string first, second;
    std::ifstream ifs("Songs.csv");

    while (std::getline(ifs, line))
    {
        std::istringstream iss(line);
        std::getline(iss, first, ',');
        std::getline(iss, second, ',');
        result.push_back(std::make_pair(first, second));
    }

    for (std::vector<std::pair<std::string, std::string>>::const_iterator it = result.cbegin(); it != result.cend(); ++it)
    {
        std::cout << it->first << " : " << it->second << '\n';
    }

    return 0;
}

如果您有超过 2 列(多于一首歌曲),更安全的解决方案是遍历从 CSV 文件中检索到的行并将其附加到 std::map&lt;std::string, std::vector&lt;std::string&gt;&gt;,其中键是乐队的名称.

编辑

这是另一个使用std::map 的解决方案,其中第一个成员是乐队的名称。如果您有两个以上的列(多于一首歌曲)并且 CSV 文件的最后一列是乐队的名称,则首选此列。

例如,您可以拥有以下 CSV 文件:

The Pretender,AAAA,Foo Fighters
In Bloom,BBBB,Nivana
Champagne Supernova,CCCC,Oasis
Starlight,DDDD,Muse
Will We Talk?,EEEE,FFFF,Sam Fender
#include <sstream>
#include <string>
#include <fstream>
#include <iostream>
#include <map>
#include <vector>

int main()
{
    std::map<std::string, std::vector<std::string>> result;
    std::string line;
    std::ifstream ifs("Songs.csv");
    int i = 0;

    while (std::getline(ifs, line))
    {
        std::istringstream iss(line);
        std::vector<std::string> temp;
        for (std::string token; std::getline(iss, token, ','); )
        {
            temp.push_back(token);
        }

        result[temp[temp.size() - 1]].insert(result[temp[temp.size() - 1]].end(), std::make_move_iterator(temp.begin()), std::make_move_iterator(temp.end() - 1));
    }

    for (std::map<std::string, std::vector<std::string>>::const_iterator it = result.cbegin(); it != result.cend(); ++it)
    {
        std::cout << it->first << " : ";

        for (std::vector<std::string>::const_iterator vit = it->second.cbegin(); vit != it->second.cend(); ++vit)
        {
            std::cout << *vit << ' ';
        }

        std::cout << '\n';
    }
}

【讨论】:

    【解决方案2】:

    问题在于&gt;&gt; 只在空格周围分割单词(换行符、制表符、空格)。

    受this question 的启发,您可以将分隔符更改为逗号,如下所示:

    #include <locale>
    #include <iostream>
    
    
    struct comma_is_space : std::ctype<char> {
      comma_is_space() : std::ctype<char>(get_table()) {}
      static mask const* get_table()
      {
        static mask rc[table_size];
        rc[','] = std::ctype_base::space;  // split on commas
        return &rc[0];
      }
    };
    
    {
        ...
        std::istringstream iss(line);
        iss.imbue(std::locale(iss.getloc(), new comma_is_space()));
        ...
    }
    

    【讨论】:

    • 简单的std::getline(stream, text, ',')怎么了?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-04
    • 1970-01-01
    • 2016-07-26
    • 1970-01-01
    • 1970-01-01
    • 2011-09-22
    相关资源
    最近更新 更多