C ++でCSVファイルを読み取って解析する方法は?
C ++でCSVファイルを解析するには、ライブラリを使用する必要があります。自分でファイルを読み取ると見逃す可能性がある場合が多いためです。 C ++用のBoostライブラリは、CSVファイルを読み取るための非常に優れたツールセットを提供します。たとえば、
#include<iostream>
vector<string> parseCSVLine(string line){
using namespace boost;
std::vector<std::string> vec;
// Tokenizes the input string
tokenizer<escaped_list_separator<char> > tk(line, escaped_list_separator<char>
('\\', ',', '\"'));
for (auto i = tk.begin(); i!=tk.end(); ++i)
vec.push_back(*i);
return vec;
}
int main() {
std::string line = "hello,from,here";
auto words = parseCSVLine(line);
for(auto it = words.begin(); it != words.end(); it++) {
std::cout << *it << std::endl;
}
} hello from here
別の方法は、区切り文字を使用して行を分割し、配列に取り込むことです-
別の方法は、getline関数を使用して文字列を分割するカスタム区切り文字を提供することです-
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main() {
std::stringstream str_strm("hello,from,here");
std::string tmp;
vector<string> words;
char delim = ','; // Ddefine the delimiter to split by
while (std::getline(str_strm, tmp, delim)) {
// Provide proper checks here for tmp like if empty
// Also strip down symbols like !, ., ?, etc.
// Finally push it.
words.push_back(tmp);
}
for(auto it = words.begin(); it != words.end(); it++) {
std::cout << *it << std::endl;
}
} hello from here
-
PythonでUnicode(UTF-8)ファイルを読み書きする方法は?
ioモジュールが推奨され、Python 3のオープン構文と互換性があります。次のコードは、Pythonでunicode(UTF-8)ファイルの読み取りと書き込みに使用されます 例 import io with io.open(filename,'r',encoding='utf8') as f: text = f.read() # process Unicode text with io.open(filename,'w',encoding='utf8') as f: f.w
-
RubyでCSVファイルを読み取って解析する方法
CSVは「カンマ区切り値」の略です。 これは、値がコンマで区切られた行で構成される一般的なデータ形式です。データのエクスポートとインポートに使用されます。 例 : Gmailの連絡先をCSVファイルとしてエクスポートできます。また、同じ形式を使用してインポートすることもできます。 これはCSVファイルの外観です : id,name 1,chocolate 2,bacon 3,apple 4,banana 5,almonds 次に、RubyCSVライブラリの使用方法を学習します。 CSVファイルの読み取りと書き込み。 RubyCSV解析 RubyにはCSVライブラリが組み込まれて